2007-06-05 Johannes Schmid <johannes.schmid@openismus.com>
[modest] / src / maemo / modest-maemo-utils.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #ifndef DBUS_API_SUBJECT_TO_CHANGE
31 #define DBUS_API_SUBJECT_TO_CHANGE
32 #endif /*DBUS_API_SUBJECT_TO_CHANGE*/
33
34 #include <dbus/dbus.h>
35 #include <dbus/dbus-glib-lowlevel.h>
36 #include <glib.h>
37 #include <modest-runtime.h>
38 #include <libgnomevfs/gnome-vfs.h>
39 #include <tny-fs-stream.h>
40 #include <tny-camel-account.h>
41 #include <tny-status.h>
42 #include <tny-camel-transport-account.h>
43 #include <tny-camel-imap-store-account.h>
44 #include <tny-camel-pop-store-account.h>
45 #include "modest-hildon-includes.h"
46
47 #include "modest-maemo-utils.h"
48
49 /*
50  * For getting and tracking the Bluetooth name
51  */
52 #define BTNAME_SERVICE                  "org.bluez"
53 #define BTNAME_REQUEST_IF               "org.bluez.Adapter"
54 #define BTNAME_SIGNAL_IF                "org.bluez.Adapter"
55 #define BTNAME_REQUEST_PATH             "/org/bluez/hci0"
56 #define BTNAME_SIGNAL_PATH              "/org/bluez/hci0"
57
58 #define BTNAME_REQ_GET                  "GetName"
59 #define BTNAME_SIG_CHANGED              "NameChanged"
60
61 #define BTNAME_MATCH_RULE "type='signal',interface='" BTNAME_SIGNAL_IF \
62                           "',member='" BTNAME_SIG_CHANGED "'"
63
64
65 GtkWidget*
66 modest_maemo_utils_menubar_to_menu (GtkUIManager *ui_manager)
67 {
68         GtkWidget *main_menu;
69         GtkWidget *menubar;
70         GList *iter;
71
72         g_return_val_if_fail (ui_manager, NULL);
73         
74         /* Create new main menu */
75         main_menu = gtk_menu_new();
76
77         /* Get the menubar from the UI manager */
78         menubar = gtk_ui_manager_get_widget (ui_manager, "/MenuBar");
79
80         iter = gtk_container_get_children (GTK_CONTAINER (menubar));
81         while (iter) {
82                 GtkWidget *menu;
83
84                 menu = GTK_WIDGET (iter->data);
85                 gtk_widget_reparent(menu, main_menu);
86
87                 iter = g_list_next (iter);
88         }
89         return main_menu;
90 }
91
92
93 static void
94 update_device_name_from_msg (DBusMessage *message)
95 {
96         DBusError error;
97         DBusMessageIter iter;
98
99         dbus_error_init (&error);
100
101         if (dbus_set_error_from_message (&error, message)) {
102                 g_printerr ("modest: failed to get bluetooth name: %s\n", error.message);
103                 dbus_error_free (&error);
104         } else {
105                 const gchar *device_name;
106                 if (!dbus_message_iter_init (message, &iter)) {
107                         g_printerr ("modest: message did not have argument\n");
108                         return;
109                 }
110                 dbus_message_iter_get_basic (&iter, &device_name);
111                 g_warning ("update device name: %s", device_name);
112                 modest_conf_set_string (modest_runtime_get_conf(),
113                                         MODEST_CONF_DEVICE_NAME, device_name,
114                                         NULL);
115         }
116 }
117
118
119 static void
120 on_device_name_received (DBusPendingCall *call, void *user_data)
121 {
122         DBusMessage *message;
123         
124         g_return_if_fail (dbus_pending_call_get_completed (call));
125         
126         message = dbus_pending_call_steal_reply (call);
127         if (!message) {
128                 g_printerr ("modest: no reply on device name query\n");
129                 return;
130         }
131
132         update_device_name_from_msg (message);
133         dbus_message_unref (message);
134 }
135
136
137 static DBusHandlerResult
138 handle_dbus_signal (DBusConnection *conn, DBusMessage *msg, gpointer data)
139 {
140         if (dbus_message_is_signal(msg, BTNAME_SIGNAL_IF, BTNAME_SIG_CHANGED))
141                 update_device_name_from_msg (msg);
142
143         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
144 }
145
146
147 static void
148 get_device_name_from_dbus ()
149 {
150         static DBusConnection *conn = NULL;
151         DBusMessage *request;
152         DBusError error;
153         DBusPendingCall *call = NULL;
154         
155         dbus_error_init (&error);
156         if (!conn) {
157                 conn = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
158                 if (!conn) {
159                         g_printerr ("modest: cannot get on the dbus: %s: %s\n",
160                                     error.name, error.message);
161                         dbus_error_free (&error);
162                         return;
163                 }
164         }
165         
166         request = dbus_message_new_method_call (BTNAME_SERVICE, BTNAME_REQUEST_PATH,
167                                                 BTNAME_REQUEST_IF, BTNAME_REQ_GET);
168         if (!request) {
169                 /* should we free the connection? */
170                 g_printerr ("modest: dbus_message_new_method_call failed\n");
171                 return;
172         }
173         dbus_message_set_auto_start (request, TRUE);
174         if (dbus_connection_send_with_reply (conn, request, &call, -1)) {
175                 dbus_pending_call_set_notify (call, on_device_name_received,
176                                               NULL, NULL);
177                 dbus_pending_call_unref (call);
178         }
179         dbus_message_unref (request);
180         
181         dbus_connection_setup_with_g_main (conn, NULL);
182         dbus_bus_add_match (conn, BTNAME_MATCH_RULE, &error);
183         if (dbus_error_is_set(&error)) {
184                 g_printerr ("modest: dbus_bus_add_match failed: %s\n", error.message);
185                 dbus_error_free (&error);
186         }
187
188         if (!dbus_connection_add_filter(conn, handle_dbus_signal, NULL, NULL))
189                 g_printerr ("modest: dbus_connection_add_filter failed\n");
190 }
191
192
193 void
194 modest_maemo_utils_get_device_name (void)
195 {
196         get_device_name_from_dbus ();
197 }
198
199 gboolean 
200 modest_maemo_utils_folder_writable (const gchar *filename)
201 {
202         if (g_strncasecmp (filename, "obex", 4) != 0) {
203                 GnomeVFSFileInfo folder_info;
204                 gchar *folder;
205                 folder = g_path_get_dirname (filename);
206                 gnome_vfs_get_file_info (folder, &folder_info,
207                                          GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
208                 g_free (folder);
209                 if (!((folder_info.permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
210                       (folder_info.permissions & GNOME_VFS_PERM_USER_WRITE))) {
211                         return FALSE;
212                 }
213         }
214         return TRUE;
215 }
216
217 gboolean 
218 modest_maemo_utils_file_exists (const gchar *filename)
219 {
220         GnomeVFSURI *uri = NULL;
221         gboolean result = FALSE;
222
223         uri = gnome_vfs_uri_new (filename);
224         if (uri) {
225                 result = gnome_vfs_uri_exists (uri);
226                 gnome_vfs_uri_unref (uri);
227         }
228         return result;
229 }
230
231 TnyFsStream *
232 modest_maemo_utils_create_temp_stream (const gchar *extension, gchar **path)
233 {
234         TnyStream *tmp_fs_stream = NULL;
235         gint fd;
236         gchar *filepath = NULL;
237         gchar *template = NULL;
238
239         if (extension != NULL)
240                 template = g_strdup_printf ("XXXXXX.%s", extension);
241
242         fd = g_file_open_tmp (template, &filepath, NULL);
243         g_free (template);
244         if (path != NULL)
245                 *path = filepath;
246         if (fd == -1) {
247                 g_message ("TODO BANNER: Error saving stream");
248                 return NULL;
249         }
250         tmp_fs_stream = tny_fs_stream_new (fd);
251         
252         return TNY_FS_STREAM (tmp_fs_stream);
253 }
254
255 typedef struct 
256 {
257         gboolean finished;
258         gboolean cancel;
259         GList *result;
260         GtkWidget* dialog;
261   GtkWidget* progress;
262 } ModestGetSupportedAuthInfo;
263
264 static void on_camel_account_get_supported_secure_authentication_status (
265         GObject *self, TnyStatus *status, gpointer user_data)
266 {
267         /*ModestGetSupportedAuthInfo* info = (ModestGetSupportedAuthInfo*) user_data;*/
268 }
269
270 static void
271 on_camel_account_get_supported_secure_authentication (
272   TnyCamelAccount *self, gboolean cancelled,
273   TnyList *auth_types, GError **err, 
274   gpointer user_data)
275 {
276                 
277         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
278         g_return_if_fail (info);
279         
280         if (!auth_types) {
281                 printf ("DEBUG: %s: auth_types is NULL.\n", __FUNCTION__);
282                 info->finished = TRUE; /* We are blocking, waiting for this. */
283                 return;
284         }
285                 
286         ModestPairList* pairs = modest_protocol_info_get_auth_protocol_pair_list ();
287   
288         /* Get the enum value for the strings: */
289         GList *result = NULL;
290         TnyIterator* iter = tny_list_create_iterator(auth_types);
291         while (!tny_iterator_is_done(iter)) {
292                 const gchar *auth_name = tny_pair_get_name(TNY_PAIR(tny_iterator_get_current(iter)));
293                 printf("DEBUG: %s: auth_name=%s\n", __FUNCTION__, auth_name);
294                 ModestPair *matching = modest_pair_list_find_by_first_as_string (pairs, 
295                         auth_name);
296                 if (matching)
297     {
298       result = g_list_append (result, GINT_TO_POINTER((ModestConnectionProtocol)matching->first));
299     }
300                 tny_iterator_next(iter);
301         }
302         
303   g_object_unref(auth_types);
304         
305         modest_pair_list_free (pairs);
306         
307         info->result = result;
308   printf("DEBUG: finished\n");
309         info->finished = TRUE; /* We are blocking, waiting for this. */
310 }
311
312 static void on_secure_auth_cancel(GtkWidget* dialog, int response, gpointer user_data)
313 {
314         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
315         g_return_if_fail(info);
316         /* We are blocking */
317         info->result = NULL;
318         info->cancel = TRUE;
319 }
320
321 GList* modest_maemo_utils_get_supported_secure_authentication_methods (ModestTransportStoreProtocol proto, 
322         const gchar* hostname, gint port, GtkWindow *parent_window)
323 {
324         g_return_val_if_fail (proto != MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN, NULL);
325         
326         /*
327         result = g_list_append (result, GINT_TO_POINTER (MODEST_PROTOCOL_AUTH_CRAMMD5));
328         */
329         
330         /* Create a TnyCamelAccount so we can use 
331          * tny_camel_account_get_supported_secure_authentication(): */
332         TnyAccount * tny_account = NULL;
333         switch (proto) {
334         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
335         case MODEST_PROTOCOL_TRANSPORT_SMTP:
336                 tny_account = TNY_ACCOUNT(tny_camel_transport_account_new ()); break;
337         case MODEST_PROTOCOL_STORE_POP:
338                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
339         case MODEST_PROTOCOL_STORE_IMAP:
340                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
341         case MODEST_PROTOCOL_STORE_MAILDIR:
342         case MODEST_PROTOCOL_STORE_MBOX:
343                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
344         default:
345                 tny_account = NULL;
346         }
347         
348         if (!tny_account) {
349                 g_printerr ("%s could not create tny account.", __FUNCTION__);
350                 return NULL;
351         }
352         
353         /* Set proto, so that the prepare_func() vfunc will work when we call 
354          * set_session(): */
355          /* TODO: Why isn't this done in account_new()? */
356         tny_account_set_proto (tny_account,
357                                modest_protocol_info_get_transport_store_protocol_name(proto));
358                                
359         /* Set the session for the account, so we can use it: */
360         ModestTnyAccountStore *account_store = modest_runtime_get_account_store ();
361         TnySessionCamel *session = 
362                 modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
363         g_return_val_if_fail (session, NULL);
364         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
365         
366         tny_account_set_hostname (tny_account, hostname);
367         
368         if(port > 0)
369                 tny_account_set_port (tny_account, port);
370                 
371
372         /* Ask camel to ask the server, asynchronously: */
373         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
374         info->finished = FALSE;
375         info->result = NULL;
376         info->progress = gtk_progress_bar_new();
377   info->dialog = gtk_dialog_new_with_buttons(_("Checking for supported authentication types"),
378                                                                                                                                 parent_window, GTK_DIALOG_MODAL,
379                                                                                                                                 GTK_STOCK_CANCEL,
380                                                                                                                                 GTK_RESPONSE_REJECT,
381                                                                                                                                 NULL);
382         
383         g_signal_connect(G_OBJECT(info->dialog), "response", G_CALLBACK(on_secure_auth_cancel), info);
384         
385         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), info->progress);
386         gtk_widget_show(info->progress);
387         gtk_widget_show(info->dialog);
388   gtk_progress_bar_pulse(GTK_PROGRESS_BAR(info->progress));
389         
390         printf ("DEBUG: %s: STARTING.\n", __FUNCTION__);
391         tny_camel_account_get_supported_secure_authentication (
392                 TNY_CAMEL_ACCOUNT (tny_account),
393                 on_camel_account_get_supported_secure_authentication,
394                 on_camel_account_get_supported_secure_authentication_status,
395                 info);
396                 
397         /* Block until the callback has been called,
398          * driving the main context, so that the (idle handler) callback can be 
399          * called, and so that our dialog is clickable: */
400         while (!(info->finished) && (!info->cancel)) {
401     gtk_main_iteration_do(FALSE); 
402         }
403         
404   gtk_widget_destroy(info->dialog);
405                 
406         GList *result = info->result;
407         g_slice_free (ModestGetSupportedAuthInfo, info);
408         info = NULL;
409         
410         return result;
411 }