]> git.0d.be Git - empathy.git/blob - src/empathy-event-manager.c
Merge branch 'sasl'
[empathy.git] / src / empathy-event-manager.c
1 /*
2  * Copyright (C) 2007-2008 Collabora Ltd.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  *
18  * Authors: Xavier Claessens <xclaesse@gmail.com>
19  *          Sjoerd Simons <sjoerd.simons@collabora.co.uk>
20  */
21
22 #include <config.h>
23
24 #include <string.h>
25 #include <glib/gi18n.h>
26
27 #include <telepathy-glib/account-manager.h>
28 #include <telepathy-glib/util.h>
29 #include <telepathy-glib/interfaces.h>
30 #include <telepathy-glib/simple-approver.h>
31
32 #include <libempathy/empathy-idle.h>
33 #include <libempathy/empathy-tp-contact-factory.h>
34 #include <libempathy/empathy-contact-manager.h>
35 #include <libempathy/empathy-tp-chat.h>
36 #include <libempathy/empathy-tp-call.h>
37 #include <libempathy/empathy-tp-file.h>
38 #include <libempathy/empathy-utils.h>
39 #include <libempathy/empathy-call-factory.h>
40 #include <libempathy/empathy-gsettings.h>
41
42 #include <extensions/extensions.h>
43
44 #include <libempathy-gtk/empathy-images.h>
45 #include <libempathy-gtk/empathy-contact-dialogs.h>
46 #include <libempathy-gtk/empathy-sound-manager.h>
47
48 #include "empathy-event-manager.h"
49 #include "empathy-main-window.h"
50
51 #define DEBUG_FLAG EMPATHY_DEBUG_DISPATCHER
52 #include <libempathy/empathy-debug.h>
53
54 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyEventManager)
55
56 #define NOTIFICATION_TIMEOUT 2 /* seconds */
57
58 /* The time interval in milliseconds between 2 incoming rings */
59 #define MS_BETWEEN_RING 500
60
61 typedef struct {
62   EmpathyEventManager *manager;
63   TpChannelDispatchOperation *operation;
64   gulong invalidated_handler;
65   /* Remove contact if applicable */
66   EmpathyContact *contact;
67   /* option signal handler and it's instance */
68   gulong handler;
69   GObject *handler_instance;
70   /* optional accept widget */
71   GtkWidget *dialog;
72   /* Channel of the CDO that will be used during the approval */
73   TpChannel *main_channel;
74   gboolean auto_approved;
75 } EventManagerApproval;
76
77 typedef struct {
78   TpBaseClient *approver;
79   EmpathyContactManager *contact_manager;
80   GSList *events;
81   /* Ongoing approvals */
82   GSList *approvals;
83
84   gint ringing;
85
86   GSettings *gsettings_notif;
87   GSettings *gsettings_ui;
88
89   EmpathySoundManager *sound_mgr;
90 } EmpathyEventManagerPriv;
91
92 typedef struct _EventPriv EventPriv;
93 typedef void (*EventFunc) (EventPriv *event);
94
95 struct _EventPriv {
96   EmpathyEvent public;
97   EmpathyEventManager *manager;
98   EventManagerApproval *approval;
99   EventFunc func;
100   gboolean inhibit;
101   gpointer user_data;
102   guint autoremove_timeout_id;
103 };
104
105 enum {
106   EVENT_ADDED,
107   EVENT_REMOVED,
108   EVENT_UPDATED,
109   LAST_SIGNAL
110 };
111
112 static guint signals[LAST_SIGNAL];
113
114 G_DEFINE_TYPE (EmpathyEventManager, empathy_event_manager, G_TYPE_OBJECT);
115
116 static EmpathyEventManager * manager_singleton = NULL;
117
118 static EventManagerApproval *
119 event_manager_approval_new (EmpathyEventManager *manager,
120   TpChannelDispatchOperation *operation,
121   TpChannel *main_channel)
122 {
123   EventManagerApproval *result = g_slice_new0 (EventManagerApproval);
124   result->operation = g_object_ref (operation);
125   result->manager = manager;
126   result->main_channel = g_object_ref (main_channel);
127
128   return result;
129 }
130
131 static void
132 event_manager_approval_free (EventManagerApproval *approval)
133 {
134   g_signal_handler_disconnect (approval->operation,
135     approval->invalidated_handler);
136   g_object_unref (approval->operation);
137
138   g_object_unref (approval->main_channel);
139
140   if (approval->handler != 0)
141     g_signal_handler_disconnect (approval->handler_instance,
142       approval->handler);
143
144   if (approval->handler_instance != NULL)
145     g_object_unref (approval->handler_instance);
146
147   if (approval->contact != NULL)
148     g_object_unref (approval->contact);
149
150   if (approval->dialog != NULL)
151     {
152       gtk_widget_destroy (approval->dialog);
153     }
154
155   g_slice_free (EventManagerApproval, approval);
156 }
157
158 static void
159 event_free (EventPriv *event)
160 {
161   g_free (event->public.icon_name);
162   g_free (event->public.header);
163   g_free (event->public.message);
164
165   if (event->autoremove_timeout_id != 0)
166     g_source_remove (event->autoremove_timeout_id);
167
168   if (event->public.contact)
169     {
170       g_object_unref (event->public.contact);
171     }
172
173   g_slice_free (EventPriv, event);
174 }
175
176 static void
177 event_remove (EventPriv *event)
178 {
179   EmpathyEventManagerPriv *priv = GET_PRIV (event->manager);
180
181   DEBUG ("Removing event %p", event);
182
183   priv->events = g_slist_remove (priv->events, event);
184   g_signal_emit (event->manager, signals[EVENT_REMOVED], 0, event);
185   event_free (event);
186 }
187
188 void
189 empathy_event_remove (EmpathyEvent *event_public)
190 {
191   EventPriv *event = (EventPriv *) event_public;
192
193   event_remove (event);
194 }
195
196 static gboolean
197 autoremove_event_timeout_cb (EventPriv *event)
198 {
199   event->autoremove_timeout_id = 0;
200   event_remove (event);
201   return FALSE;
202 }
203
204 static gboolean
205 display_notify_area (EmpathyEventManager *self)
206 {
207   EmpathyEventManagerPriv *priv = GET_PRIV (self);
208
209   return g_settings_get_boolean (priv->gsettings_ui,
210       EMPATHY_PREFS_UI_EVENTS_NOTIFY_AREA);
211 }
212
213 static void
214 event_manager_add (EmpathyEventManager *manager,
215     EmpathyContact *contact,
216     EmpathyEventType type,
217     const gchar *icon_name,
218     const gchar *header,
219     const gchar *message,
220     EventManagerApproval *approval,
221     EventFunc func,
222     gpointer user_data)
223 {
224   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
225   EventPriv               *event;
226
227   event = g_slice_new0 (EventPriv);
228   event->public.contact = contact ? g_object_ref (contact) : NULL;
229   event->public.type = type;
230   event->public.icon_name = g_strdup (icon_name);
231   event->public.header = g_strdup (header);
232   event->public.message = g_strdup (message);
233   event->public.must_ack = (func != NULL);
234   event->inhibit = FALSE;
235   event->func = func;
236   event->user_data = user_data;
237   event->manager = manager;
238   event->approval = approval;
239
240   DEBUG ("Adding event %p", event);
241   priv->events = g_slist_prepend (priv->events, event);
242
243   if (!display_notify_area (manager))
244     {
245       /* Don't fire the 'event-added' signal as we activate the event now */
246       if (approval != NULL)
247         approval->auto_approved = TRUE;
248
249       empathy_event_activate (&event->public);
250       return;
251     }
252
253   g_signal_emit (event->manager, signals[EVENT_ADDED], 0, event);
254
255   if (!event->public.must_ack)
256     {
257       event->autoremove_timeout_id = g_timeout_add_seconds (
258           NOTIFICATION_TIMEOUT, (GSourceFunc) autoremove_event_timeout_cb,
259           event);
260     }
261 }
262
263 static void
264 handle_with_cb (GObject *source,
265     GAsyncResult *result,
266     gpointer user_data)
267 {
268   TpChannelDispatchOperation *cdo = TP_CHANNEL_DISPATCH_OPERATION (source);
269   GError *error = NULL;
270
271   if (!tp_channel_dispatch_operation_handle_with_finish (cdo, result, &error))
272     {
273       DEBUG ("HandleWith failed: %s\n", error->message);
274       g_error_free (error);
275     }
276 }
277
278 static void
279 handle_with_time_cb (GObject *source,
280     GAsyncResult *result,
281     gpointer user_data)
282 {
283   TpChannelDispatchOperation *cdo = TP_CHANNEL_DISPATCH_OPERATION (source);
284   GError *error = NULL;
285
286   if (!tp_channel_dispatch_operation_handle_with_time_finish (cdo, result,
287         &error))
288     {
289       if (g_error_matches (error, TP_ERRORS, TP_ERROR_NOT_IMPLEMENTED))
290         {
291           EventManagerApproval *approval = user_data;
292
293           DEBUG ("HandleWithTime() is not implemented, falling back to "
294               "HandleWith(). Please upgrade to telepathy-mission-control "
295               "5.5.0 or later");
296
297           tp_channel_dispatch_operation_handle_with_async (approval->operation,
298               NULL, handle_with_cb, approval);
299         }
300       else
301         {
302           DEBUG ("HandleWithTime failed: %s\n", error->message);
303         }
304       g_error_free (error);
305     }
306 }
307
308 static void
309 event_manager_approval_approve (EventManagerApproval *approval)
310 {
311   gint64 timestamp;
312
313   if (approval->auto_approved)
314     {
315       timestamp = TP_USER_ACTION_TIME_NOT_USER_ACTION;
316     }
317   else
318     {
319       timestamp = tp_user_action_time_from_x11 (gtk_get_current_event_time ());
320     }
321
322   g_assert (approval->operation != NULL);
323
324   tp_channel_dispatch_operation_handle_with_time_async (approval->operation,
325       NULL, timestamp, handle_with_time_cb, approval);
326 }
327
328 static void
329 event_channel_process_func (EventPriv *event)
330 {
331   event_manager_approval_approve (event->approval);
332 }
333
334 static void
335 event_text_channel_process_func (EventPriv *event)
336 {
337   EmpathyTpChat *tp_chat;
338   gint64 timestamp;
339
340   timestamp = tp_user_action_time_from_x11 (gtk_get_current_event_time ());
341
342   if (event->approval->handler != 0)
343     {
344       tp_chat = EMPATHY_TP_CHAT (event->approval->handler_instance);
345
346       g_signal_handler_disconnect (tp_chat, event->approval->handler);
347       event->approval->handler = 0;
348     }
349
350   event_manager_approval_approve (event->approval);
351 }
352
353 static EventPriv *
354 event_lookup_by_approval (EmpathyEventManager *manager,
355   EventManagerApproval *approval)
356 {
357   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
358   GSList *l;
359   EventPriv *retval = NULL;
360
361   for (l = priv->events; l; l = l->next)
362     {
363       EventPriv *event = l->data;
364
365       if (event->approval == approval)
366         {
367           retval = event;
368           break;
369         }
370     }
371
372   return retval;
373 }
374
375 static void
376 event_update (EmpathyEventManager *manager, EventPriv *event,
377   const char *icon_name, const char *header, const char *msg)
378 {
379   g_free (event->public.icon_name);
380   g_free (event->public.header);
381   g_free (event->public.message);
382
383   event->public.icon_name = g_strdup (icon_name);
384   event->public.header = g_strdup (header);
385   event->public.message = g_strdup (msg);
386
387   g_signal_emit (manager, signals[EVENT_UPDATED], 0, event);
388 }
389
390 static void
391 reject_channel_claim_cb (GObject *source,
392     GAsyncResult *result,
393     gpointer user_data)
394 {
395   TpChannelDispatchOperation *cdo = TP_CHANNEL_DISPATCH_OPERATION (source);
396   GError *error = NULL;
397
398   if (!tp_channel_dispatch_operation_claim_finish (cdo, result, &error))
399     {
400       DEBUG ("Failed to claim channel: %s", error->message);
401
402       g_error_free (error);
403       goto out;
404     }
405
406   if (EMPATHY_IS_TP_CALL (user_data))
407     {
408       empathy_tp_call_close (user_data);
409     }
410   else if (EMPATHY_IS_TP_CHAT (user_data))
411     {
412       empathy_tp_chat_leave (user_data);
413     }
414   else if (EMPATHY_IS_TP_FILE (user_data))
415     {
416       empathy_tp_file_close (user_data);
417     }
418
419 out:
420   g_object_unref (user_data);
421 }
422
423 static void
424 reject_approval (EventManagerApproval *approval)
425 {
426   /* We have to claim the channel before closing it */
427   tp_channel_dispatch_operation_claim_async (approval->operation,
428       reject_channel_claim_cb, g_object_ref (approval->handler_instance));
429 }
430
431 static void
432 event_manager_call_window_confirmation_dialog_response_cb (GtkDialog *dialog,
433   gint response, gpointer user_data)
434 {
435   EventManagerApproval *approval = user_data;
436
437   gtk_widget_destroy (approval->dialog);
438   approval->dialog = NULL;
439
440   if (response != GTK_RESPONSE_ACCEPT)
441     {
442       reject_approval (approval);
443     }
444   else
445     {
446       event_manager_approval_approve (approval);
447     }
448 }
449
450 static void
451 event_channel_process_voip_func (EventPriv *event)
452 {
453   GtkWidget *dialog;
454   GtkWidget *button;
455   GtkWidget *image;
456   EmpathyTpCall *call;
457   gboolean video;
458   gchar *title;
459
460   if (event->approval->dialog != NULL)
461     {
462       gtk_window_present (GTK_WINDOW (event->approval->dialog));
463       return;
464     }
465
466   call = EMPATHY_TP_CALL (event->approval->handler_instance);
467
468   video = empathy_tp_call_has_initial_video (call);
469
470   dialog = gtk_message_dialog_new (NULL, 0,
471       GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
472       video ? _("Incoming video call"): _("Incoming call"));
473
474   gtk_message_dialog_format_secondary_text (
475     GTK_MESSAGE_DIALOG (dialog), video ?
476       _("%s is video calling you. Do you want to answer?"):
477       _("%s is calling you. Do you want to answer?"),
478       empathy_contact_get_alias (event->approval->contact));
479
480   title = g_strdup_printf (_("Incoming call from %s"),
481       empathy_contact_get_alias (event->approval->contact));
482
483   gtk_window_set_title (GTK_WINDOW (dialog), title);
484   g_free (title);
485
486   /* Set image of the dialog */
487   if (video)
488     {
489       image = gtk_image_new_from_icon_name (EMPATHY_IMAGE_VIDEO_CALL,
490           GTK_ICON_SIZE_DIALOG);
491     }
492   else
493     {
494       image = gtk_image_new_from_icon_name (EMPATHY_IMAGE_VOIP,
495           GTK_ICON_SIZE_DIALOG);
496     }
497
498   gtk_message_dialog_set_image (GTK_MESSAGE_DIALOG (dialog), image);
499   gtk_widget_show (image);
500
501   gtk_dialog_set_default_response (GTK_DIALOG (dialog),
502       GTK_RESPONSE_OK);
503
504   button = gtk_dialog_add_button (GTK_DIALOG (dialog),
505       _("_Reject"), GTK_RESPONSE_REJECT);
506   image = gtk_image_new_from_icon_name ("call-stop",
507     GTK_ICON_SIZE_BUTTON);
508   gtk_button_set_image (GTK_BUTTON (button), image);
509
510   button = gtk_dialog_add_button (GTK_DIALOG (dialog),
511       _("_Answer"), GTK_RESPONSE_ACCEPT);
512
513   image = gtk_image_new_from_icon_name ("call-start", GTK_ICON_SIZE_BUTTON);
514   gtk_button_set_image (GTK_BUTTON (button), image);
515
516   g_signal_connect (dialog, "response",
517       G_CALLBACK (event_manager_call_window_confirmation_dialog_response_cb),
518       event->approval);
519
520   gtk_widget_show (dialog);
521
522   event->approval->dialog = dialog;
523 }
524
525 static void
526 event_manager_chat_message_received_cb (EmpathyTpChat *tp_chat,
527   EmpathyMessage *message,
528   EventManagerApproval *approval)
529 {
530   GtkWidget       *window = empathy_main_window_dup ();
531   EmpathyContact  *sender;
532   const gchar     *header;
533   const gchar     *msg;
534   TpChannel       *channel;
535   EventPriv       *event;
536   EmpathyEventManagerPriv *priv = GET_PRIV (approval->manager);
537
538   /* try to update the event if it's referring to a chat which is already in the
539    * queue. */
540   event = event_lookup_by_approval (approval->manager, approval);
541
542   sender = empathy_message_get_sender (message);
543   header = empathy_contact_get_alias (sender);
544   msg = empathy_message_get_body (message);
545
546   channel = empathy_tp_chat_get_channel (tp_chat);
547
548   if (event != NULL)
549     event_update (approval->manager, event, EMPATHY_IMAGE_NEW_MESSAGE, header,
550         msg);
551   else
552     event_manager_add (approval->manager, sender, EMPATHY_EVENT_TYPE_CHAT,
553         EMPATHY_IMAGE_NEW_MESSAGE, header, msg, approval,
554         event_text_channel_process_func, NULL);
555
556   empathy_sound_manager_play (priv->sound_mgr, window,
557       EMPATHY_SOUND_CONVERSATION_NEW);
558
559   g_object_unref (window);
560 }
561
562 static void
563 event_manager_approval_done (EventManagerApproval *approval)
564 {
565   EmpathyEventManagerPriv *priv = GET_PRIV (approval->manager);
566   GSList                  *l;
567
568   if (approval->operation != NULL)
569     {
570       GQuark channel_type;
571
572       channel_type = tp_channel_get_channel_type_id (approval->main_channel);
573
574       if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_STREAMED_MEDIA)
575         {
576           priv->ringing--;
577           if (priv->ringing == 0)
578             empathy_sound_manager_stop (priv->sound_mgr,
579                 EMPATHY_SOUND_PHONE_INCOMING);
580         }
581     }
582
583   priv->approvals = g_slist_remove (priv->approvals, approval);
584
585   for (l = priv->events; l; l = l->next)
586     {
587       EventPriv *event = l->data;
588
589       if (event->approval == approval)
590         {
591           event_remove (event);
592           break;
593         }
594     }
595
596   event_manager_approval_free (approval);
597 }
598
599 static void
600 cdo_invalidated_cb (TpProxy *cdo,
601     guint domain,
602     gint code,
603     gchar *message,
604     EventManagerApproval *approval)
605 {
606   DEBUG ("ChannelDispatchOperation has been invalidated: %s", message);
607
608   event_manager_approval_done (approval);
609 }
610
611 static void
612 event_manager_media_channel_got_contact (EventManagerApproval *approval)
613 {
614   EmpathyEventManagerPriv *priv = GET_PRIV (approval->manager);
615   GtkWidget *window = empathy_main_window_dup ();
616   gchar *header;
617   EmpathyTpCall *call;
618   gboolean video;
619
620   call = EMPATHY_TP_CALL (approval->handler_instance);
621
622   video = empathy_tp_call_has_initial_video (call);
623
624   header = g_strdup_printf (
625     video ? _("Incoming video call from %s") :_("Incoming call from %s"),
626     empathy_contact_get_alias (approval->contact));
627
628   event_manager_add (approval->manager, approval->contact,
629       EMPATHY_EVENT_TYPE_VOIP,
630       video ? EMPATHY_IMAGE_VIDEO_CALL : EMPATHY_IMAGE_VOIP,
631       header, NULL, approval,
632       event_channel_process_voip_func, NULL);
633
634   g_free (header);
635
636   priv->ringing++;
637   if (priv->ringing == 1)
638     empathy_sound_manager_start_playing (priv->sound_mgr, window,
639         EMPATHY_SOUND_PHONE_INCOMING, MS_BETWEEN_RING);
640
641   g_object_unref (window);
642 }
643
644 static void
645 event_manager_media_channel_contact_changed_cb (EmpathyTpCall *call,
646   GParamSpec *param, EventManagerApproval *approval)
647 {
648   EmpathyContact *contact;
649
650   g_object_get (G_OBJECT (call), "contact", &contact, NULL);
651
652   if (contact == NULL)
653     return;
654
655   approval->contact = contact;
656   event_manager_media_channel_got_contact (approval);
657 }
658
659 static void
660 invite_dialog_response_cb (GtkDialog *dialog,
661                            gint response,
662                            EventManagerApproval *approval)
663 {
664   EmpathyTpChat *tp_chat;
665
666   gtk_widget_destroy (GTK_WIDGET (approval->dialog));
667   approval->dialog = NULL;
668
669   tp_chat = EMPATHY_TP_CHAT (approval->handler_instance);
670
671   if (response != GTK_RESPONSE_OK)
672     {
673       /* close channel */
674       DEBUG ("Muc invitation rejected");
675
676       reject_approval (approval);
677
678       return;
679     }
680
681   DEBUG ("Muc invitation accepted");
682
683   /* We'll join the room when handling the channel */
684   event_manager_approval_approve (approval);
685 }
686
687 static void
688 event_room_channel_process_func (EventPriv *event)
689 {
690   GtkWidget *dialog, *button, *image;
691   TpChannel *channel = event->approval->main_channel;
692   gchar *title;
693
694   if (event->approval->dialog != NULL)
695     {
696       gtk_window_present (GTK_WINDOW (event->approval->dialog));
697       return;
698     }
699
700   /* create dialog */
701   dialog = gtk_message_dialog_new (NULL, 0,
702       GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Room invitation"));
703
704   title = g_strdup_printf (_("Invitation to join %s"),
705       tp_channel_get_identifier (channel));
706
707   gtk_window_set_title (GTK_WINDOW (dialog), title);
708   g_free (title);
709
710   gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
711       _("%s is inviting you to join %s"),
712       empathy_contact_get_alias (event->approval->contact),
713       tp_channel_get_identifier (channel));
714
715   gtk_dialog_set_default_response (GTK_DIALOG (dialog),
716       GTK_RESPONSE_OK);
717
718   button = gtk_dialog_add_button (GTK_DIALOG (dialog),
719       _("_Decline"), GTK_RESPONSE_CANCEL);
720   image = gtk_image_new_from_icon_name (GTK_STOCK_CANCEL, GTK_ICON_SIZE_BUTTON);
721   gtk_button_set_image (GTK_BUTTON (button), image);
722
723   button = gtk_dialog_add_button (GTK_DIALOG (dialog),
724       _("_Join"), GTK_RESPONSE_OK);
725   image = gtk_image_new_from_icon_name (GTK_STOCK_APPLY, GTK_ICON_SIZE_BUTTON);
726   gtk_button_set_image (GTK_BUTTON (button), image);
727
728   g_signal_connect (dialog, "response",
729       G_CALLBACK (invite_dialog_response_cb), event->approval);
730
731   gtk_widget_show (dialog);
732
733   event->approval->dialog = dialog;
734 }
735
736 static void
737 display_invite_room_dialog (EventManagerApproval *approval)
738 {
739   GtkWidget *window = empathy_main_window_dup ();
740   const gchar *invite_msg;
741   gchar *msg;
742   TpHandle self_handle;
743   EmpathyEventManagerPriv *priv = GET_PRIV (approval->manager);
744
745   self_handle = tp_channel_group_get_self_handle (approval->main_channel);
746   tp_channel_group_get_local_pending_info (approval->main_channel, self_handle,
747       NULL, NULL, &invite_msg);
748
749   if (approval->contact != NULL)
750     {
751       msg = g_strdup_printf (_("%s invited you to join %s"),
752           empathy_contact_get_alias (approval->contact),
753           tp_channel_get_identifier (approval->main_channel));
754     }
755   else
756     {
757       msg = g_strdup_printf (_("You have been invited to join %s"),
758           tp_channel_get_identifier (approval->main_channel));
759     }
760
761   event_manager_add (approval->manager, approval->contact,
762       EMPATHY_EVENT_TYPE_INVITATION, EMPATHY_IMAGE_GROUP_MESSAGE, msg,
763       invite_msg, approval, event_room_channel_process_func, NULL);
764
765   empathy_sound_manager_play (priv->sound_mgr, window,
766       EMPATHY_SOUND_CONVERSATION_NEW);
767
768   g_free (msg);
769   g_object_unref (window);
770 }
771
772 static void
773 event_manager_muc_invite_got_contact_cb (TpConnection *connection,
774                                          EmpathyContact *contact,
775                                          const GError *error,
776                                          gpointer user_data,
777                                          GObject *object)
778 {
779   EventManagerApproval *approval = (EventManagerApproval *) user_data;
780
781   if (error != NULL)
782     {
783       DEBUG ("Error: %s", error->message);
784     }
785   else
786     {
787       approval->contact = g_object_ref (contact);
788     }
789
790   display_invite_room_dialog (approval);
791 }
792
793 static void
794 event_manager_ft_got_contact_cb (TpConnection *connection,
795                                  EmpathyContact *contact,
796                                  const GError *error,
797                                  gpointer user_data,
798                                  GObject *object)
799 {
800   EventManagerApproval *approval = (EventManagerApproval *) user_data;
801   GtkWidget *window = empathy_main_window_dup ();
802   char *header;
803   EmpathyEventManagerPriv *priv = GET_PRIV (approval->manager);
804
805   approval->contact = g_object_ref (contact);
806
807   header = g_strdup_printf (_("Incoming file transfer from %s"),
808                             empathy_contact_get_alias (approval->contact));
809
810   event_manager_add (approval->manager, approval->contact,
811       EMPATHY_EVENT_TYPE_TRANSFER, EMPATHY_IMAGE_DOCUMENT_SEND, header, NULL,
812       approval, event_channel_process_func, NULL);
813
814   /* FIXME better sound for incoming file transfers ?*/
815   empathy_sound_manager_play (priv->sound_mgr, window,
816       EMPATHY_SOUND_CONVERSATION_NEW);
817
818   g_free (header);
819   g_object_unref (window);
820 }
821
822 /* If there is a file-transfer or media channel consider it as the
823  * main one. */
824 static TpChannel *
825 find_main_channel (GList *channels)
826 {
827   GList *l;
828   TpChannel *text = NULL;
829
830   for (l = channels; l != NULL; l = g_list_next (l))
831     {
832       TpChannel *channel = l->data;
833       GQuark channel_type;
834
835       if (tp_proxy_get_invalidated (channel) != NULL)
836         continue;
837
838       channel_type = tp_channel_get_channel_type_id (channel);
839
840       if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_STREAMED_MEDIA ||
841           channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_FILE_TRANSFER)
842         return channel;
843
844       else if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_TEXT)
845         text = channel;
846     }
847
848   return text;
849 }
850
851 static void
852 approve_channels (TpSimpleApprover *approver,
853     TpAccount *account,
854     TpConnection *connection,
855     GList *channels,
856     TpChannelDispatchOperation *dispatch_operation,
857     TpAddDispatchOperationContext *context,
858     gpointer user_data)
859 {
860   EmpathyEventManager *self = user_data;
861   EmpathyEventManagerPriv *priv = GET_PRIV (self);
862   TpChannel *channel;
863   EventManagerApproval *approval;
864   GQuark channel_type;
865
866   channel = find_main_channel (channels);
867   if (channel == NULL)
868     {
869       GError error = { TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
870           "Unknown channel type" };
871
872       DEBUG ("Failed to find the main channel; ignoring");
873
874       tp_add_dispatch_operation_context_fail (context, &error);
875       return;
876     }
877
878   approval = event_manager_approval_new (self, dispatch_operation, channel);
879   priv->approvals = g_slist_prepend (priv->approvals, approval);
880
881   approval->invalidated_handler = g_signal_connect (dispatch_operation,
882       "invalidated", G_CALLBACK (cdo_invalidated_cb), approval);
883
884   channel_type = tp_channel_get_channel_type_id (channel);
885
886   if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_TEXT)
887     {
888       EmpathyTpChat *tp_chat;
889
890       tp_chat = empathy_tp_chat_new (account, channel);
891       approval->handler_instance = G_OBJECT (tp_chat);
892
893       if (tp_proxy_has_interface (channel, TP_IFACE_CHANNEL_INTERFACE_GROUP))
894         {
895           /* Are we in local-pending ? */
896           TpHandle inviter;
897
898           if (empathy_tp_chat_is_invited (tp_chat, &inviter))
899             {
900               /* We are invited to a room */
901               DEBUG ("Have been invited to %s. Ask user if he wants to accept",
902                   tp_channel_get_identifier (channel));
903
904               if (inviter != 0)
905                 {
906                   empathy_tp_contact_factory_get_from_handle (connection,
907                       inviter, event_manager_muc_invite_got_contact_cb,
908                       approval, NULL, G_OBJECT (self));
909                 }
910               else
911                 {
912                   display_invite_room_dialog (approval);
913                 }
914
915               goto out;
916             }
917
918           /* We are not invited, approve the channel right now */
919           tp_add_dispatch_operation_context_accept (context);
920
921           approval->auto_approved = TRUE;
922           event_manager_approval_approve (approval);
923           return;
924         }
925
926       /* 1-1 text channel, wait for the first message */
927       approval->handler = g_signal_connect (tp_chat, "message-received",
928         G_CALLBACK (event_manager_chat_message_received_cb), approval);
929     }
930   else if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_STREAMED_MEDIA)
931     {
932       EmpathyContact *contact;
933       EmpathyTpCall *call = empathy_tp_call_new (account, channel);
934
935       approval->handler_instance = G_OBJECT (call);
936
937       g_object_get (G_OBJECT (call), "contact", &contact, NULL);
938
939       if (contact == NULL)
940         {
941           g_signal_connect (call, "notify::contact",
942             G_CALLBACK (event_manager_media_channel_contact_changed_cb),
943             approval);
944         }
945       else
946         {
947           approval->contact = contact;
948           event_manager_media_channel_got_contact (approval);
949         }
950
951     }
952   else if (channel_type == TP_IFACE_QUARK_CHANNEL_TYPE_FILE_TRANSFER)
953     {
954       TpHandle handle;
955       EmpathyTpFile *tp_file = empathy_tp_file_new (channel);
956
957       approval->handler_instance = G_OBJECT (tp_file);
958
959       handle = tp_channel_get_handle (channel, NULL);
960
961       connection = tp_channel_borrow_connection (channel);
962       empathy_tp_contact_factory_get_from_handle (connection, handle,
963         event_manager_ft_got_contact_cb, approval, NULL, G_OBJECT (self));
964     }
965   else
966     {
967       GError error = { TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
968           "Invalid channel type" };
969
970       DEBUG ("Unknown channel type (%s), ignoring..",
971           g_quark_to_string (channel_type));
972
973       tp_add_dispatch_operation_context_fail (context, &error);
974       return;
975     }
976
977 out:
978   tp_add_dispatch_operation_context_accept (context);
979 }
980
981 static void
982 event_pending_subscribe_func (EventPriv *event)
983 {
984   empathy_subscription_dialog_show (event->public.contact, event->public.header,
985       NULL);
986   event_remove (event);
987 }
988
989 static void
990 event_manager_pendings_changed_cb (EmpathyContactList  *list,
991   EmpathyContact *contact, EmpathyContact *actor,
992   guint reason, gchar *message, gboolean is_pending,
993   EmpathyEventManager *manager)
994 {
995   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
996   gchar                   *header, *event_msg;
997
998   if (!is_pending)
999     {
1000       GSList *l;
1001
1002       for (l = priv->events; l; l = l->next)
1003         {
1004           EventPriv *event = l->data;
1005
1006           if (event->public.contact == contact &&
1007               event->func == event_pending_subscribe_func)
1008             {
1009               event_remove (event);
1010               break;
1011             }
1012         }
1013
1014       return;
1015     }
1016
1017   header = g_strdup_printf (
1018       _("%s would like permission to see when you are available"),
1019       empathy_contact_get_alias (contact));
1020
1021   if (!EMP_STR_EMPTY (message))
1022     event_msg = g_strdup_printf (_("\nMessage: %s"), message);
1023   else
1024     event_msg = NULL;
1025
1026   event_manager_add (manager, contact, EMPATHY_EVENT_TYPE_SUBSCRIPTION,
1027       GTK_STOCK_DIALOG_QUESTION, header, event_msg, NULL,
1028       event_pending_subscribe_func, NULL);
1029
1030   g_free (event_msg);
1031   g_free (header);
1032 }
1033
1034 static void
1035 event_manager_presence_changed_cb (EmpathyContact *contact,
1036     TpConnectionPresenceType current,
1037     TpConnectionPresenceType previous,
1038     EmpathyEventManager *manager)
1039 {
1040   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
1041   TpAccount *account;
1042   gchar *header = NULL;
1043   EmpathyIdle *idle;
1044   GtkWidget *window = empathy_main_window_dup ();
1045
1046   account = empathy_contact_get_account (contact);
1047   idle = empathy_idle_dup_singleton ();
1048
1049   if (empathy_idle_account_is_just_connected (idle, account))
1050     goto out;
1051
1052   if (tp_connection_presence_type_cmp_availability (previous,
1053         TP_CONNECTION_PRESENCE_TYPE_OFFLINE) > 0)
1054     {
1055       /* contact was online */
1056       if (tp_connection_presence_type_cmp_availability (current,
1057           TP_CONNECTION_PRESENCE_TYPE_OFFLINE) <= 0)
1058         {
1059           /* someone is logging off */
1060           empathy_sound_manager_play (priv->sound_mgr, window,
1061               EMPATHY_SOUND_CONTACT_DISCONNECTED);
1062
1063           if (g_settings_get_boolean (priv->gsettings_notif,
1064                 EMPATHY_PREFS_NOTIFICATIONS_CONTACT_SIGNOUT))
1065             {
1066               header = g_strdup_printf (_("%s is now offline."),
1067                   empathy_contact_get_alias (contact));
1068
1069               event_manager_add (manager, contact, EMPATHY_EVENT_TYPE_PRESENCE,
1070                   EMPATHY_IMAGE_AVATAR_DEFAULT, header, NULL, NULL, NULL, NULL);
1071             }
1072         }
1073     }
1074   else
1075     {
1076       /* contact was offline */
1077       if (tp_connection_presence_type_cmp_availability (current,
1078             TP_CONNECTION_PRESENCE_TYPE_OFFLINE) > 0)
1079         {
1080           /* someone is logging in */
1081           empathy_sound_manager_play (priv->sound_mgr, window,
1082               EMPATHY_SOUND_CONTACT_CONNECTED);
1083
1084           if (g_settings_get_boolean (priv->gsettings_notif,
1085                 EMPATHY_PREFS_NOTIFICATIONS_CONTACT_SIGNIN))
1086             {
1087               header = g_strdup_printf (_("%s is now online."),
1088                   empathy_contact_get_alias (contact));
1089
1090               event_manager_add (manager, contact, EMPATHY_EVENT_TYPE_PRESENCE,
1091                   EMPATHY_IMAGE_AVATAR_DEFAULT, header, NULL, NULL, NULL, NULL);
1092             }
1093         }
1094     }
1095   g_free (header);
1096
1097 out:
1098   g_object_unref (idle);
1099   g_object_unref (window);
1100 }
1101
1102 static void
1103 event_manager_members_changed_cb (EmpathyContactList  *list,
1104     EmpathyContact *contact,
1105     EmpathyContact *actor,
1106     guint reason,
1107     gchar *message,
1108     gboolean is_member,
1109     EmpathyEventManager *manager)
1110 {
1111   if (is_member)
1112     g_signal_connect (contact, "presence-changed",
1113         G_CALLBACK (event_manager_presence_changed_cb), manager);
1114   else
1115     g_signal_handlers_disconnect_by_func (contact,
1116         event_manager_presence_changed_cb, manager);
1117 }
1118
1119 static GObject *
1120 event_manager_constructor (GType type,
1121                            guint n_props,
1122                            GObjectConstructParam *props)
1123 {
1124         GObject *retval;
1125
1126         if (manager_singleton) {
1127                 retval = g_object_ref (manager_singleton);
1128         } else {
1129                 retval = G_OBJECT_CLASS (empathy_event_manager_parent_class)->constructor
1130                         (type, n_props, props);
1131
1132                 manager_singleton = EMPATHY_EVENT_MANAGER (retval);
1133                 g_object_add_weak_pointer (retval, (gpointer) &manager_singleton);
1134         }
1135
1136         return retval;
1137 }
1138
1139 static void
1140 event_manager_finalize (GObject *object)
1141 {
1142   EmpathyEventManagerPriv *priv = GET_PRIV (object);
1143
1144   if (priv->ringing > 0)
1145     empathy_sound_manager_stop (priv->sound_mgr, EMPATHY_SOUND_PHONE_INCOMING);
1146
1147   g_slist_foreach (priv->events, (GFunc) event_free, NULL);
1148   g_slist_free (priv->events);
1149   g_slist_foreach (priv->approvals, (GFunc) event_manager_approval_free, NULL);
1150   g_slist_free (priv->approvals);
1151   g_object_unref (priv->contact_manager);
1152   g_object_unref (priv->approver);
1153   g_object_unref (priv->gsettings_notif);
1154   g_object_unref (priv->gsettings_ui);
1155   g_object_unref (priv->sound_mgr);
1156 }
1157
1158 static void
1159 empathy_event_manager_class_init (EmpathyEventManagerClass *klass)
1160 {
1161   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1162
1163   object_class->finalize = event_manager_finalize;
1164   object_class->constructor = event_manager_constructor;
1165
1166   signals[EVENT_ADDED] =
1167     g_signal_new ("event-added",
1168       G_TYPE_FROM_CLASS (klass),
1169       G_SIGNAL_RUN_LAST,
1170       0,
1171       NULL, NULL,
1172       g_cclosure_marshal_VOID__POINTER,
1173       G_TYPE_NONE,
1174       1, G_TYPE_POINTER);
1175
1176   signals[EVENT_REMOVED] =
1177   g_signal_new ("event-removed",
1178       G_TYPE_FROM_CLASS (klass),
1179       G_SIGNAL_RUN_LAST,
1180       0,
1181       NULL, NULL,
1182       g_cclosure_marshal_VOID__POINTER,
1183       G_TYPE_NONE, 1, G_TYPE_POINTER);
1184
1185   signals[EVENT_UPDATED] =
1186   g_signal_new ("event-updated",
1187       G_TYPE_FROM_CLASS (klass),
1188       G_SIGNAL_RUN_LAST,
1189       0,
1190       NULL, NULL,
1191       g_cclosure_marshal_VOID__POINTER,
1192       G_TYPE_NONE, 1, G_TYPE_POINTER);
1193
1194
1195   g_type_class_add_private (object_class, sizeof (EmpathyEventManagerPriv));
1196 }
1197
1198 static void
1199 empathy_event_manager_init (EmpathyEventManager *manager)
1200 {
1201   EmpathyEventManagerPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (manager,
1202     EMPATHY_TYPE_EVENT_MANAGER, EmpathyEventManagerPriv);
1203   TpDBusDaemon *dbus;
1204   GError *error = NULL;
1205
1206   manager->priv = priv;
1207
1208   priv->gsettings_notif = g_settings_new (EMPATHY_PREFS_NOTIFICATIONS_SCHEMA);
1209   priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
1210
1211   priv->sound_mgr = empathy_sound_manager_dup_singleton ();
1212
1213   priv->contact_manager = empathy_contact_manager_dup_singleton ();
1214   g_signal_connect (priv->contact_manager, "pendings-changed",
1215     G_CALLBACK (event_manager_pendings_changed_cb), manager);
1216
1217   g_signal_connect (priv->contact_manager, "members-changed",
1218     G_CALLBACK (event_manager_members_changed_cb), manager);
1219
1220   dbus = tp_dbus_daemon_dup (&error);
1221   if (dbus == NULL)
1222     {
1223       DEBUG ("Failed to get TpDBusDaemon: %s", error->message);
1224       g_error_free (error);
1225       return;
1226     }
1227
1228   priv->approver = tp_simple_approver_new (dbus, "Empathy.EventManager", FALSE,
1229       approve_channels, manager, NULL);
1230
1231   /* EmpathyTpChat relies on this feature being prepared */
1232   tp_base_client_add_connection_features_varargs (priv->approver,
1233     TP_CONNECTION_FEATURE_CAPABILITIES, 0);
1234
1235   /* Private text channels */
1236   tp_base_client_take_approver_filter (priv->approver,
1237       tp_asv_new (
1238         TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TEXT,
1239         TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
1240         NULL));
1241
1242   /* Muc text channels */
1243   tp_base_client_take_approver_filter (priv->approver,
1244       tp_asv_new (
1245         TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TEXT,
1246         TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_ROOM,
1247         NULL));
1248
1249   /* File transfer */
1250   tp_base_client_take_approver_filter (priv->approver,
1251       tp_asv_new (
1252         TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1253           TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
1254         TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
1255         NULL));
1256
1257   /* Calls */
1258   tp_base_client_take_approver_filter (priv->approver,
1259       tp_asv_new (
1260         TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1261           TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
1262         TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
1263         NULL));
1264
1265   if (!tp_base_client_register (priv->approver, &error))
1266     {
1267       DEBUG ("Failed to register Approver: %s", error->message);
1268       g_error_free (error);
1269     }
1270
1271   g_object_unref (dbus);
1272 }
1273
1274 EmpathyEventManager *
1275 empathy_event_manager_dup_singleton (void)
1276 {
1277   return g_object_new (EMPATHY_TYPE_EVENT_MANAGER, NULL);
1278 }
1279
1280 GSList *
1281 empathy_event_manager_get_events (EmpathyEventManager *manager)
1282 {
1283   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
1284
1285   g_return_val_if_fail (EMPATHY_IS_EVENT_MANAGER (manager), NULL);
1286
1287   return priv->events;
1288 }
1289
1290 EmpathyEvent *
1291 empathy_event_manager_get_top_event (EmpathyEventManager *manager)
1292 {
1293   EmpathyEventManagerPriv *priv = GET_PRIV (manager);
1294
1295   g_return_val_if_fail (EMPATHY_IS_EVENT_MANAGER (manager), NULL);
1296
1297   return priv->events ? priv->events->data : NULL;
1298 }
1299
1300 void
1301 empathy_event_activate (EmpathyEvent *event_public)
1302 {
1303   EventPriv *event = (EventPriv *) event_public;
1304
1305   g_return_if_fail (event_public != NULL);
1306
1307   if (event->func)
1308     event->func (event);
1309   else
1310     event_remove (event);
1311 }
1312
1313 void
1314 empathy_event_inhibit_updates (EmpathyEvent *event_public)
1315 {
1316   EventPriv *event = (EventPriv *) event_public;
1317
1318   g_return_if_fail (event_public != NULL);
1319
1320   event->inhibit = TRUE;
1321 }
1322
1323 void
1324 empathy_event_approve (EmpathyEvent *event_public)
1325 {
1326   EventPriv *event = (EventPriv *) event_public;
1327
1328   g_return_if_fail (event_public != NULL);
1329
1330   event_manager_approval_approve (event->approval);
1331 }
1332
1333 void
1334 empathy_event_decline (EmpathyEvent *event_public)
1335 {
1336   EventPriv *event = (EventPriv *) event_public;
1337
1338   g_return_if_fail (event_public != NULL);
1339
1340   reject_approval (event->approval);
1341 }