Use new getters and setters of EmpathyChatroom. Simplify to lookup when a tp_chat...
[empathy.git] / libempathy / empathy-chatroom-manager.c
1 /*
2  * Copyright (C) 2004-2007 Imendio AB
3  * Copyright (C) 2007-2009 Collabora Ltd.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Authors: Xavier Claessens <xclaesse@gmail.com>
21  *          Martyn Russell <martyn@imendio.com>
22  */
23
24 #include "config.h"
25
26 #include <string.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include <libxml/parser.h>
31 #include <libxml/tree.h>
32
33 #include "empathy-tp-chat.h"
34 #include "empathy-chatroom-manager.h"
35 #include "empathy-account-manager.h"
36 #include "empathy-utils.h"
37
38 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
39 #include "empathy-debug.h"
40
41 #define CHATROOMS_XML_FILENAME "chatrooms.xml"
42 #define CHATROOMS_DTD_FILENAME "empathy-chatroom-manager.dtd"
43 #define SAVE_TIMER 4
44
45 static EmpathyChatroomManager *chatroom_manager_singleton = NULL;
46
47 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChatroomManager)
48 typedef struct
49 {
50   GList *chatrooms;
51   gchar *file;
52   EmpathyAccountManager *account_manager;
53   /* source id of the autosave timer */
54   gint save_timer_id;
55 } EmpathyChatroomManagerPriv;
56
57 enum {
58   CHATROOM_ADDED,
59   CHATROOM_REMOVED,
60   LAST_SIGNAL
61 };
62
63 static guint signals[LAST_SIGNAL];
64
65 /* properties */
66 enum
67 {
68   PROP_FILE = 1,
69   LAST_PROPERTY
70 };
71
72 G_DEFINE_TYPE (EmpathyChatroomManager, empathy_chatroom_manager, G_TYPE_OBJECT);
73
74 /*
75  * API to save/load and parse the chatrooms file.
76  */
77
78 static gboolean
79 chatroom_manager_file_save (EmpathyChatroomManager *manager)
80 {
81         EmpathyChatroomManagerPriv *priv;
82         xmlDocPtr                  doc;
83         xmlNodePtr                 root;
84         GList                     *l;
85
86         priv = GET_PRIV (manager);
87
88         doc = xmlNewDoc ("1.0");
89         root = xmlNewNode (NULL, "chatrooms");
90         xmlDocSetRootElement (doc, root);
91
92         for (l = priv->chatrooms; l; l = l->next) {
93                 EmpathyChatroom *chatroom;
94                 xmlNodePtr       node;
95                 const gchar     *account_id;
96
97                 chatroom = l->data;
98
99                 if (!empathy_chatroom_is_favorite (chatroom)) {
100                         continue;
101                 }
102
103                 account_id = mc_account_get_unique_name (empathy_chatroom_get_account (chatroom));
104
105                 node = xmlNewChild (root, NULL, "chatroom", NULL);
106                 xmlNewTextChild (node, NULL, "name", empathy_chatroom_get_name (chatroom));
107                 xmlNewTextChild (node, NULL, "room", empathy_chatroom_get_room (chatroom));
108                 xmlNewTextChild (node, NULL, "account", account_id);
109                 xmlNewTextChild (node, NULL, "auto_connect",
110                         empathy_chatroom_get_auto_connect (chatroom) ? "yes" : "no");
111         }
112
113         /* Make sure the XML is indented properly */
114         xmlIndentTreeOutput = 1;
115
116         DEBUG ("Saving file:'%s'", priv->file);
117         xmlSaveFormatFileEnc (priv->file, doc, "utf-8", 1);
118         xmlFreeDoc (doc);
119
120         xmlCleanupParser ();
121         xmlMemoryDump ();
122
123         return TRUE;
124 }
125
126 static gboolean
127 save_timeout (EmpathyChatroomManager *self)
128 {
129   EmpathyChatroomManagerPriv *priv = GET_PRIV (self);
130
131   priv->save_timer_id = 0;
132   chatroom_manager_file_save (self);
133
134   return FALSE;
135 }
136
137 static void
138 reset_save_timeout (EmpathyChatroomManager *self)
139 {
140   EmpathyChatroomManagerPriv *priv = GET_PRIV (self);
141
142   if (priv->save_timer_id > 0)
143     {
144       g_source_remove (priv->save_timer_id);
145     }
146
147   priv->save_timer_id = g_timeout_add_seconds (SAVE_TIMER,
148       (GSourceFunc) save_timeout, self);
149 }
150
151 static void
152 chatroom_changed_cb (EmpathyChatroom *chatroom,
153                      GParamSpec *spec,
154                      EmpathyChatroomManager *self)
155 {
156   reset_save_timeout (self);
157 }
158
159 static void
160 add_chatroom (EmpathyChatroomManager *self,
161               EmpathyChatroom *chatroom)
162 {
163   EmpathyChatroomManagerPriv *priv = GET_PRIV (self);
164
165   priv->chatrooms = g_list_prepend (priv->chatrooms, g_object_ref (chatroom));
166
167   g_signal_connect (chatroom, "notify",
168       G_CALLBACK (chatroom_changed_cb), self);
169 }
170
171 static void
172 chatroom_manager_parse_chatroom (EmpathyChatroomManager *manager,
173                                  xmlNodePtr             node)
174 {
175         EmpathyChatroomManagerPriv *priv;
176         EmpathyChatroom            *chatroom;
177         McAccount                 *account;
178         xmlNodePtr                 child;
179         gchar                     *str;
180         gchar                     *name;
181         gchar                     *room;
182         gchar                     *account_id;
183         gboolean                   auto_connect;
184
185         priv = GET_PRIV (manager);
186
187         /* default values. */
188         name = NULL;
189         room = NULL;
190         auto_connect = TRUE;
191         account_id = NULL;
192
193         for (child = node->children; child; child = child->next) {
194                 gchar *tag;
195
196                 if (xmlNodeIsText (child)) {
197                         continue;
198                 }
199
200                 tag = (gchar *) child->name;
201                 str = (gchar *) xmlNodeGetContent (child);
202
203                 if (strcmp (tag, "name") == 0) {
204                         name = g_strdup (str);
205                 }
206                 else if (strcmp (tag, "room") == 0) {
207                         room = g_strdup (str);
208                 }
209                 else if (strcmp (tag, "auto_connect") == 0) {
210                         if (strcmp (str, "yes") == 0) {
211                                 auto_connect = TRUE;
212                         } else {
213                                 auto_connect = FALSE;
214                         }
215                 }
216                 else if (strcmp (tag, "account") == 0) {
217                         account_id = g_strdup (str);
218                 }
219
220                 xmlFree (str);
221         }
222
223         account = mc_account_lookup (account_id);
224         if (!account) {
225                 g_free (name);
226                 g_free (room);
227                 g_free (account_id);
228                 return;
229         }
230
231         chatroom = empathy_chatroom_new_full (account, room, name, auto_connect);
232         empathy_chatroom_set_favorite (chatroom, TRUE);
233         add_chatroom (manager, chatroom);
234         g_signal_emit (manager, signals[CHATROOM_ADDED], 0, chatroom);
235
236         g_object_unref (account);
237         g_free (name);
238         g_free (room);
239         g_free (account_id);
240 }
241
242 static gboolean
243 chatroom_manager_file_parse (EmpathyChatroomManager *manager,
244                              const gchar           *filename)
245 {
246         EmpathyChatroomManagerPriv *priv;
247         xmlParserCtxtPtr           ctxt;
248         xmlDocPtr                  doc;
249         xmlNodePtr                 chatrooms;
250         xmlNodePtr                 node;
251
252         priv = GET_PRIV (manager);
253
254         DEBUG ("Attempting to parse file:'%s'...", filename);
255
256         ctxt = xmlNewParserCtxt ();
257
258         /* Parse and validate the file. */
259         doc = xmlCtxtReadFile (ctxt, filename, NULL, 0);
260         if (!doc) {
261                 g_warning ("Failed to parse file:'%s'", filename);
262                 xmlFreeParserCtxt (ctxt);
263                 return FALSE;
264         }
265
266         if (!empathy_xml_validate (doc, CHATROOMS_DTD_FILENAME)) {
267                 g_warning ("Failed to validate file:'%s'", filename);
268                 xmlFreeDoc(doc);
269                 xmlFreeParserCtxt (ctxt);
270                 return FALSE;
271         }
272
273         /* The root node, chatrooms. */
274         chatrooms = xmlDocGetRootElement (doc);
275
276         for (node = chatrooms->children; node; node = node->next) {
277                 if (strcmp ((gchar *) node->name, "chatroom") == 0) {
278                         chatroom_manager_parse_chatroom (manager, node);
279                 }
280         }
281
282         DEBUG ("Parsed %d chatrooms", g_list_length (priv->chatrooms));
283
284         xmlFreeDoc(doc);
285         xmlFreeParserCtxt (ctxt);
286
287         return TRUE;
288 }
289
290 static gboolean
291 chatroom_manager_get_all (EmpathyChatroomManager *manager)
292 {
293         EmpathyChatroomManagerPriv *priv;
294
295         priv = GET_PRIV (manager);
296
297         /* read file in */
298         if (g_file_test (priv->file, G_FILE_TEST_EXISTS) &&
299             !chatroom_manager_file_parse (manager, priv->file)) {
300                 return FALSE;
301         }
302
303         return TRUE;
304 }
305
306 static void
307 empathy_chatroom_manager_get_property (GObject *object,
308                                        guint property_id,
309                                        GValue *value,
310                                        GParamSpec *pspec)
311 {
312   EmpathyChatroomManager *self = EMPATHY_CHATROOM_MANAGER (object);
313   EmpathyChatroomManagerPriv *priv = GET_PRIV (self);
314
315   switch (property_id)
316     {
317       case PROP_FILE:
318         g_value_set_string (value, priv->file);
319         break;
320       default:
321         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
322         break;
323     }
324 }
325
326 static void
327 empathy_chatroom_manager_set_property (GObject *object,
328                                        guint property_id,
329                                        const GValue *value,
330                                        GParamSpec *pspec)
331 {
332   EmpathyChatroomManager *self = EMPATHY_CHATROOM_MANAGER (object);
333   EmpathyChatroomManagerPriv *priv = GET_PRIV (self);
334
335   switch (property_id)
336     {
337       case PROP_FILE:
338         g_free (priv->file);
339         priv->file = g_value_dup_string (value);
340         break;
341       default:
342         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
343         break;
344     }
345 }
346
347 static void
348 chatroom_manager_finalize (GObject *object)
349 {
350   EmpathyChatroomManager *self = EMPATHY_CHATROOM_MANAGER (object);
351   EmpathyChatroomManagerPriv *priv;
352   GList *l;
353
354   priv = GET_PRIV (object);
355
356   g_object_unref (priv->account_manager);
357
358   if (priv->save_timer_id > 0)
359     {
360       /* have to save before destroy the object */
361       g_source_remove (priv->save_timer_id);
362       priv->save_timer_id = 0;
363       chatroom_manager_file_save (self);
364     }
365
366   for (l = priv->chatrooms; l != NULL; l = g_list_next (l))
367     {
368       EmpathyChatroom *chatroom = l->data;
369
370       g_signal_handlers_disconnect_by_func (chatroom, chatroom_changed_cb,
371           self);
372
373       g_object_unref (chatroom);
374     }
375
376   g_list_free (priv->chatrooms);
377   g_free (priv->file);
378
379   (G_OBJECT_CLASS (empathy_chatroom_manager_parent_class)->finalize) (object);
380 }
381
382 static GObject *
383 empathy_chatroom_manager_constructor (GType type,
384                                       guint n_props,
385                                       GObjectConstructParam *props)
386 {
387   GObject *obj;
388   EmpathyChatroomManager *self;
389   EmpathyChatroomManagerPriv *priv;
390
391   if (chatroom_manager_singleton != NULL)
392     return g_object_ref (chatroom_manager_singleton);
393
394   /* Parent constructor chain */
395   obj = G_OBJECT_CLASS (empathy_chatroom_manager_parent_class)->
396         constructor (type, n_props, props);
397
398   self = EMPATHY_CHATROOM_MANAGER (obj);
399   priv = GET_PRIV (self);
400
401   chatroom_manager_singleton = self;
402   g_object_add_weak_pointer (obj, (gpointer) &chatroom_manager_singleton);
403
404   priv->account_manager = empathy_account_manager_dup_singleton ();
405
406   if (priv->file == NULL)
407     {
408       /* Set the default file path */
409       gchar *dir;
410
411       dir = g_build_filename (g_get_home_dir (), ".gnome2", PACKAGE_NAME, NULL);
412       if (!g_file_test (dir, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))
413         g_mkdir_with_parents (dir, S_IRUSR | S_IWUSR | S_IXUSR);
414
415       priv->file = g_build_filename (dir, CHATROOMS_XML_FILENAME, NULL);
416       g_free (dir);
417     }
418
419   chatroom_manager_get_all (self);
420   return obj;
421 }
422
423 static void
424 empathy_chatroom_manager_class_init (EmpathyChatroomManagerClass *klass)
425 {
426   GObjectClass *object_class = G_OBJECT_CLASS (klass);
427   GParamSpec *param_spec;
428
429   object_class->constructor = empathy_chatroom_manager_constructor;
430   object_class->get_property = empathy_chatroom_manager_get_property;
431   object_class->set_property = empathy_chatroom_manager_set_property;
432         object_class->finalize = chatroom_manager_finalize;
433
434   param_spec = g_param_spec_string (
435       "file",
436       "path of the favorite file",
437       "The path of the XML file containing user's favorites",
438       NULL,
439       G_PARAM_CONSTRUCT_ONLY |
440       G_PARAM_READWRITE |
441       G_PARAM_STATIC_NAME |
442       G_PARAM_STATIC_NICK |
443       G_PARAM_STATIC_BLURB);
444   g_object_class_install_property (object_class, PROP_FILE, param_spec);
445
446   signals[CHATROOM_ADDED] = g_signal_new ("chatroom-added",
447       G_TYPE_FROM_CLASS (klass),
448       G_SIGNAL_RUN_LAST,
449       0, NULL, NULL,
450       g_cclosure_marshal_VOID__OBJECT,
451       G_TYPE_NONE,
452       1, EMPATHY_TYPE_CHATROOM);
453
454   signals[CHATROOM_REMOVED] = g_signal_new ("chatroom-removed",
455       G_TYPE_FROM_CLASS (klass),
456       G_SIGNAL_RUN_LAST,
457       0, NULL, NULL,
458       g_cclosure_marshal_VOID__OBJECT,
459       G_TYPE_NONE,
460       1, EMPATHY_TYPE_CHATROOM);
461
462   g_type_class_add_private (object_class, sizeof (EmpathyChatroomManagerPriv));
463 }
464
465 static void
466 empathy_chatroom_manager_init (EmpathyChatroomManager *manager)
467 {
468   EmpathyChatroomManagerPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (manager,
469       EMPATHY_TYPE_CHATROOM_MANAGER, EmpathyChatroomManagerPriv);
470
471   manager->priv = priv;
472 }
473
474 EmpathyChatroomManager *
475 empathy_chatroom_manager_dup_singleton (const gchar *file)
476 {
477   return EMPATHY_CHATROOM_MANAGER (g_object_new (EMPATHY_TYPE_CHATROOM_MANAGER,
478       "file", file, NULL));
479 }
480
481 gboolean
482 empathy_chatroom_manager_add (EmpathyChatroomManager *manager,
483                              EmpathyChatroom        *chatroom)
484 {
485   EmpathyChatroomManagerPriv *priv;
486
487   g_return_val_if_fail (EMPATHY_IS_CHATROOM_MANAGER (manager), FALSE);
488   g_return_val_if_fail (EMPATHY_IS_CHATROOM (chatroom), FALSE);
489
490   priv = GET_PRIV (manager);
491
492   /* don't add more than once */
493   if (!empathy_chatroom_manager_find (manager,
494       empathy_chatroom_get_account (chatroom),
495       empathy_chatroom_get_room (chatroom)))
496     {
497       add_chatroom (manager, chatroom);
498
499       if (empathy_chatroom_is_favorite (chatroom))
500         reset_save_timeout (manager);
501
502       g_signal_emit (manager, signals[CHATROOM_ADDED], 0, chatroom);
503       return TRUE;
504     }
505
506   return FALSE;
507 }
508
509 void
510 empathy_chatroom_manager_remove (EmpathyChatroomManager *manager,
511                                  EmpathyChatroom        *chatroom)
512 {
513   EmpathyChatroomManagerPriv *priv;
514   GList *l;
515
516   g_return_if_fail (EMPATHY_IS_CHATROOM_MANAGER (manager));
517   g_return_if_fail (EMPATHY_IS_CHATROOM (chatroom));
518
519   priv = GET_PRIV (manager);
520
521   for (l = priv->chatrooms; l; l = l->next)
522     {
523       EmpathyChatroom *this_chatroom;
524
525       this_chatroom = l->data;
526
527       if (this_chatroom == chatroom ||
528           empathy_chatroom_equal (chatroom, this_chatroom))
529         {
530           priv->chatrooms = g_list_delete_link (priv->chatrooms, l);
531           if (empathy_chatroom_is_favorite (chatroom))
532             reset_save_timeout (manager);
533
534           g_signal_emit (manager, signals[CHATROOM_REMOVED], 0, this_chatroom);
535           g_signal_handlers_disconnect_by_func (chatroom, chatroom_changed_cb,
536               manager);
537
538           g_object_unref (this_chatroom);
539           break;
540         }
541     }
542 }
543
544 EmpathyChatroom *
545 empathy_chatroom_manager_find (EmpathyChatroomManager *manager,
546                                McAccount *account,
547                                const gchar *room)
548 {
549         EmpathyChatroomManagerPriv *priv;
550         GList                     *l;
551
552         g_return_val_if_fail (EMPATHY_IS_CHATROOM_MANAGER (manager), NULL);
553         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
554         g_return_val_if_fail (room != NULL, NULL);
555
556         priv = GET_PRIV (manager);
557
558         for (l = priv->chatrooms; l; l = l->next) {
559                 EmpathyChatroom *chatroom;
560                 McAccount      *this_account;
561                 const gchar    *this_room;
562
563                 chatroom = l->data;
564                 this_account = empathy_chatroom_get_account (chatroom);
565                 this_room = empathy_chatroom_get_room (chatroom);
566
567                 if (this_account && this_room &&
568                     empathy_account_equal (account, this_account) &&
569                     strcmp (this_room, room) == 0) {
570                         return chatroom;
571                 }
572         }
573
574         return NULL;
575 }
576
577 GList *
578 empathy_chatroom_manager_get_chatrooms (EmpathyChatroomManager *manager,
579                                        McAccount             *account)
580 {
581         EmpathyChatroomManagerPriv *priv;
582         GList                     *chatrooms, *l;
583
584         g_return_val_if_fail (EMPATHY_IS_CHATROOM_MANAGER (manager), NULL);
585
586         priv = GET_PRIV (manager);
587
588         if (!account) {
589                 return g_list_copy (priv->chatrooms);
590         }
591
592         chatrooms = NULL;
593         for (l = priv->chatrooms; l; l = l->next) {
594                 EmpathyChatroom *chatroom;
595
596                 chatroom = l->data;
597
598                 if (empathy_account_equal (account,
599                                           empathy_chatroom_get_account (chatroom))) {
600                         chatrooms = g_list_append (chatrooms, chatroom);
601                 }
602         }
603
604         return chatrooms;
605 }
606
607 guint
608 empathy_chatroom_manager_get_count (EmpathyChatroomManager *manager,
609                                    McAccount             *account)
610 {
611         EmpathyChatroomManagerPriv *priv;
612         GList                     *l;
613         guint                      count = 0;
614
615         g_return_val_if_fail (EMPATHY_IS_CHATROOM_MANAGER (manager), 0);
616
617         priv = GET_PRIV (manager);
618
619         if (!account) {
620                 return g_list_length (priv->chatrooms);
621         }
622
623         for (l = priv->chatrooms; l; l = l->next) {
624                 EmpathyChatroom *chatroom;
625
626                 chatroom = l->data;
627
628                 if (empathy_account_equal (account,
629                                            empathy_chatroom_get_account (chatroom))) {
630                         count++;
631                 }
632         }
633
634         return count;
635 }
636
637 static void
638 chatroom_manager_chat_destroyed_cb (EmpathyTpChat *chat,
639   gpointer manager)
640 {
641   EmpathyChatroomManagerPriv *priv = GET_PRIV (manager);
642   GList *l;
643
644   for (l = priv->chatrooms; l; l = l->next)
645     {
646       EmpathyChatroom *chatroom = l->data;
647
648       if (empathy_chatroom_get_tp_chat (chatroom) != chat)
649         continue;
650
651       empathy_chatroom_set_tp_chat (chatroom, NULL);
652       if (!empathy_chatroom_is_favorite (chatroom))
653         {
654           /* Remove the chatroom from the list, unless it's in the list of
655            * favourites..
656            * FIXME this policy should probably not be in libempathy */
657           empathy_chatroom_manager_remove (manager, chatroom);
658         }
659     }
660 }
661
662 static void
663 chatroom_manager_observe_channel_cb (EmpathyDispatcher *dispatcher,
664   EmpathyDispatchOperation *operation, gpointer manager)
665 {
666   EmpathyChatroomManagerPriv *priv = GET_PRIV (manager);
667   EmpathyChatroom *chatroom;
668   TpChannel *channel;
669   EmpathyTpChat *chat;
670   const gchar *roomname;
671   GQuark channel_type;
672   TpHandleType handle_type;
673   McAccount *account;
674   TpConnection *connection;
675
676   channel_type = empathy_dispatch_operation_get_channel_type_id (operation);
677
678   /* Observe Text channels to rooms only */
679   if (channel_type != TP_IFACE_QUARK_CHANNEL_TYPE_TEXT)
680     return;
681
682   channel = empathy_dispatch_operation_get_channel (operation);
683   tp_channel_get_handle (channel, &handle_type);
684
685   if (handle_type != TP_HANDLE_TYPE_ROOM)
686     return;
687
688   chat = EMPATHY_TP_CHAT (
689     empathy_dispatch_operation_get_channel_wrapper (operation));
690   connection = empathy_tp_chat_get_connection (chat);
691   account = empathy_account_manager_get_account (priv->account_manager,
692       connection);
693
694   roomname = empathy_tp_chat_get_id (chat);
695
696   chatroom = empathy_chatroom_manager_find (manager, account, roomname);
697
698   if (chatroom == NULL)
699     {
700       chatroom = empathy_chatroom_new_full (account, roomname, roomname,
701         FALSE);
702       empathy_chatroom_set_tp_chat (chatroom, chat);
703       empathy_chatroom_manager_add (manager, chatroom);
704       g_object_unref (chatroom);
705     }
706   else
707     {
708         empathy_chatroom_set_tp_chat (chatroom, chat);
709     }
710
711   /* A TpChat is always destroyed as it only gets unreffed after the channel
712    * has been invalidated in the dispatcher..  */
713   g_signal_connect (chat, "destroy",
714     G_CALLBACK (chatroom_manager_chat_destroyed_cb),
715     manager);
716 }
717
718 void
719 empathy_chatroom_manager_observe (EmpathyChatroomManager *manager,
720   EmpathyDispatcher *dispatcher)
721 {
722   g_signal_connect (dispatcher, "observe",
723     G_CALLBACK (chatroom_manager_observe_channel_cb), manager);
724 }