Implement support for federated avatars
[claws.git] / src / plugins / libravatar / libravatar.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail Team
4  * Copyright (C) 2014 Ricardo Mones
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program 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
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27
28 #include <curl/curl.h>
29
30 #include "version.h"
31 #include "libravatar.h"
32 #include "libravatar_prefs.h"
33 #include "libravatar_missing.h"
34 #include "libravatar_federation.h"
35 #include "prefs_common.h"
36 #include "procheader.h"
37 #include "procmsg.h"
38 #include "utils.h"
39 #include "md5.h"
40
41 /* indexes of keys are default_mode - 10 if applicable */
42 static const char *def_mode[] = {
43         "404",  /* not used, only useful in web pages */
44         "mm",
45         "identicon",
46         "monsterid",
47         "wavatar",
48         "retro"
49 };
50
51 static guint update_hook_id;
52 static guint render_hook_id;
53 static gchar *cache_dir = NULL; /* dir-separator terminated */
54
55 static gboolean libravatar_header_update_hook(gpointer source, gpointer data)
56 {
57         AvatarCaptureData *acd = (AvatarCaptureData *)source;
58
59         debug_print("libravatar avatar_header_update invoked\n");
60
61         if (!strcmp(acd->header, "From:")) {
62                 gchar *a, *lower;
63
64                 a = g_strdup(acd->content);
65                 extract_address(a);
66
67                 /* string to lower */
68                 for (lower = a; *lower; lower++)
69                         *lower = g_ascii_tolower(*lower);
70
71                 debug_print("libravatar added '%s'\n", a);
72                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_LIBRAVATAR, a);
73         }
74
75         return FALSE; /* keep getting */
76 }
77
78 static gchar *federated_base_url_from_address(const gchar *address)
79 {
80 #if (defined USE_GNUTLS && GLIB_CHECK_VERSION(2,22,0))
81         gchar *base_url = NULL;
82
83         if (!libravatarprefs.allow_federated) {
84                 debug_print("federated domains disabled by configuration\n");
85                 goto default_url;
86         }
87
88         base_url = federated_url_for_address(address);
89         if (base_url != NULL) {
90                 return base_url;
91         }
92
93 default_url:
94 #endif
95         return g_strdup(libravatarprefs.base_url);
96 }
97
98 static GtkWidget *image_widget_from_filename(const gchar *filename)
99 {
100         GtkWidget *image = NULL;
101         GdkPixbuf *picture = NULL;
102         GError *error = NULL;
103         gint w, h;
104
105         gdk_pixbuf_get_file_info(filename, &w, &h);
106
107         if (w != AVATAR_SIZE || h != AVATAR_SIZE)
108                 /* server can provide a different size from the requested in URL */
109                 picture = gdk_pixbuf_new_from_file_at_scale(
110                                 filename, AVATAR_SIZE, AVATAR_SIZE, TRUE, &error);
111         else    /* exact size */
112                 picture = gdk_pixbuf_new_from_file(filename, &error);
113
114         if (error != NULL) {
115                 g_warning("Failed to load image '%s': %s\n", filename, error->message);
116                 g_error_free(error);
117         } else {
118                 if (picture) {
119                         image = gtk_image_new_from_pixbuf(picture);
120                         g_object_unref(picture);
121                 } else
122                         g_warning("Failed to load image '%s': no error returned!\n", filename);
123         }
124
125         return image;
126 }
127
128 static gchar *cache_name_for_md5(const gchar *md5)
129 {
130         if (libravatarprefs.default_mode >= DEF_MODE_MM
131                         && libravatarprefs.default_mode <= DEF_MODE_RETRO) {
132                 /* cache dir for generated avatars */
133                 return g_strconcat(cache_dir, def_mode[libravatarprefs.default_mode - 10],
134                                    G_DIR_SEPARATOR_S, md5, NULL);
135         }
136         /* default cache dir */
137         return g_strconcat(cache_dir, md5, NULL);
138 }
139
140 static size_t write_image_data_cb(void *ptr, size_t size, size_t nmemb, void *stream)
141 {
142         size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
143         debug_print("received %zu bytes from avatar server\n", written);
144
145         return written;
146 }
147
148 static GtkWidget *image_widget_from_url(const gchar *url, const gchar *md5)
149 {
150         GtkWidget *image = NULL;
151         gchar *filename;
152         FILE *file;
153         CURL *curl;
154
155         curl = curl_easy_init();
156         if (curl == NULL) {
157                 g_warning("could not initialize curl to get image from url\n");
158                 return NULL;
159         }
160         curl_easy_setopt(curl, CURLOPT_URL, url);
161         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_image_data_cb);
162         curl_easy_setopt(curl, CURLOPT_TIMEOUT, prefs_common_get_prefs()->io_timeout_secs);
163         curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
164
165         filename = cache_name_for_md5(md5);
166         file = fopen(filename, "wb");
167         if (file != NULL) {
168                 long filesize;
169
170                 if (libravatarprefs.allow_redirects) {
171                         long maxredirs = (libravatarprefs.default_mode == DEF_MODE_URL)? 3L
172                                 : ((libravatarprefs.default_mode == DEF_MODE_MM)? 2L: 1L);
173
174                         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
175                         curl_easy_setopt(curl, CURLOPT_MAXREDIRS, maxredirs);
176                 }
177                 curl_easy_setopt(curl, CURLOPT_FILE, file);
178                 debug_print("retrieving URL to file: %s -> %s\n", url, filename);
179                 curl_easy_perform(curl);
180                 filesize = ftell(file);
181                 fclose(file);
182
183                 if (filesize < MIN_PNG_SIZE)
184                         debug_print("not enough data for an avatar image: %ld bytes\n", filesize);
185                 else
186                         image = image_widget_from_filename(filename);
187
188                 if (!libravatarprefs.cache_icons || filesize == 0) {
189                         if (g_unlink(filename) < 0)
190                                 g_warning("failed to delete cache file %s\n", filename);
191                 }
192
193                 if (filesize == 0)
194                         missing_add_md5(libravatarmisses, md5);
195         } else {
196                 g_warning("could not open '%s' for writting\n", filename);
197         }
198         curl_easy_cleanup(curl);
199         g_free(filename);
200
201         return image;
202 }
203
204 static gboolean is_recent_enough(const gchar *filename)
205 {
206         struct stat s;
207         time_t t;
208
209         if (libravatarprefs.cache_icons) {
210                 t = time(NULL);
211                 if (t != (time_t)-1 && !g_stat(filename, &s)) {
212                         if (t - s.st_ctime <= libravatarprefs.cache_interval * 3600)
213                                 return TRUE;
214                 }
215         }
216
217         return FALSE; /* re-download */
218 }
219
220 static GtkWidget *image_widget_from_cached_md5(const gchar *md5)
221 {
222         GtkWidget *image = NULL;
223         gchar *filename;
224
225         filename = cache_name_for_md5(md5);
226         if (is_file_exist(filename) && is_recent_enough(filename)) {
227                 debug_print("found cached image for %s\n", md5);
228                 image = image_widget_from_filename(filename);
229         }
230         g_free(filename);
231
232         return image;
233 }
234
235 static gchar *libravatar_url_for_md5(const gchar *base, const gchar *md5)
236 {
237         if (libravatarprefs.default_mode >= DEF_MODE_404) {
238                 return g_strdup_printf("%s/%s?s=%u&d=%s",
239                                 base, md5, AVATAR_SIZE,
240                                 def_mode[libravatarprefs.default_mode - 10]);
241         } else if (libravatarprefs.default_mode == DEF_MODE_URL) {
242                 return g_strdup_printf("%s/%s?s=%u&d=%s",
243                                 base, md5, AVATAR_SIZE,
244                                 libravatarprefs.default_mode_url);
245         } else if (libravatarprefs.default_mode == DEF_MODE_NONE) {
246                 return g_strdup_printf("%s/%s?s=%u",
247                                 base, md5, AVATAR_SIZE);
248         }
249
250         g_warning("invalid libravatar default mode: %d\n", libravatarprefs.default_mode);
251         return NULL;
252 }
253
254 static gboolean libravatar_image_render_hook(gpointer source, gpointer data)
255 {
256         AvatarRender *ar = (AvatarRender *)source;
257         GtkWidget *image = NULL;
258         gchar *a = NULL, *url = NULL;
259         gchar md5sum[33];
260
261         debug_print("libravatar avatar_image_render invoked\n");
262
263         a = procmsg_msginfo_get_avatar(ar->full_msginfo, AVATAR_LIBRAVATAR);
264         if (a != NULL) {
265                 gchar *base;
266
267                 md5_hex_digest(md5sum, a);
268                 /* try missing cache */
269                 if (is_missing_md5(libravatarmisses, md5sum)) {
270                         return FALSE;
271                 }
272                 /* try disk cache */
273                 image = image_widget_from_cached_md5(md5sum);
274                 if (image != NULL) {
275                         if (ar->image) /* previous plugin set one */
276                                 gtk_widget_destroy(ar->image);
277                         ar->image = image;
278                         return FALSE;
279                 }
280                 /* not cached copy: try network */
281                 if (prefs_common.work_offline) {
282                         debug_print("working off-line: libravatar network retrieval skipped\n");
283                         return FALSE;
284                 }
285                 base = federated_base_url_from_address(a);
286                 url = libravatar_url_for_md5(base, md5sum);
287                 if (url != NULL) {
288                         image = image_widget_from_url(url, md5sum);
289                         g_free(url);
290                         if (image != NULL) {
291                                 if (ar->image) /* previous plugin set one */
292                                         gtk_widget_destroy(ar->image);
293                                 ar->image = image;
294                         }
295                 }
296                 g_free(base);
297
298                 return TRUE;
299         }
300
301         return FALSE; /* keep rendering */
302 }
303
304 static gint cache_dir_init()
305 {
306         gchar *subdir;
307         int i;
308
309         cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
310                                 LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
311                                 NULL);
312         if (!is_dir_exist(cache_dir)) {
313                 if (make_dir(cache_dir) < 0) {
314                         g_free(cache_dir);
315                         return -1;
316                 }
317         }
318         for (i = DEF_MODE_MM; i <= DEF_MODE_RETRO; ++i) {
319                 subdir = g_strconcat(cache_dir, def_mode[i - 10], NULL);
320                 if (!is_dir_exist(subdir)) {
321                         if (make_dir(subdir) < 0) {
322                                 g_warning("cannot create directory %s\n", subdir);
323                                 g_free(subdir);
324                                 return -1;
325                         }
326                 }
327                 g_free(subdir);
328         }
329
330         return 0;
331 }
332
333 static gint missing_cache_init()
334 {
335         gchar *cache_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
336                                         LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
337                                         LIBRAVATAR_MISSING_FILE, NULL);
338
339         libravatarmisses = missing_load_from_file(cache_file);
340         g_free(cache_file);
341
342         if (libravatarmisses == NULL)
343                 return -1;
344
345         return 0;
346 }
347
348 static void missing_cache_done()
349 {
350         gchar *cache_file;
351
352         if (libravatarmisses != NULL) {
353                 cache_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
354                                         LIBRAVATAR_CACHE_DIR, G_DIR_SEPARATOR_S,
355                                         LIBRAVATAR_MISSING_FILE, NULL);
356                 missing_save_to_file(libravatarmisses, cache_file);
357                 g_free(cache_file);
358                 g_hash_table_destroy(libravatarmisses);
359         }
360 }
361
362 /**
363  * Initialize plugin.
364  *
365  * @param error  For storing the returned error message.
366  *
367  * @return 0 if initialization succeeds, -1 on failure.
368  */
369 gint plugin_init(gchar **error)
370 {
371         if (!check_plugin_version(MAKE_NUMERIC_VERSION(3,9,3,29),
372                                   VERSION_NUMERIC, _("Libravatar"), error))
373                 return -1;
374         /* get info from headers */
375         update_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST,
376                                              libravatar_header_update_hook,
377                                              NULL);
378         if (update_hook_id == -1) {
379                 *error = g_strdup(_("Failed to register avatar header update hook"));
380                 return -1;
381         }
382         /* get image for displaying */
383         render_hook_id = hooks_register_hook(AVATAR_IMAGE_RENDER_HOOKLIST,
384                                              libravatar_image_render_hook,
385                                              NULL);
386         if (render_hook_id == -1) {
387                 *error = g_strdup(_("Failed to register avatar image render hook"));
388                 return -1;
389         }
390         /* cache dir */
391         if (cache_dir_init() == -1) {
392                 *error = g_strdup(_("Failed to create avatar image cache directory"));
393                 return -1;
394         }
395         /* preferences page */
396         libravatar_prefs_init();
397         /* curl library */
398         curl_global_init(CURL_GLOBAL_DEFAULT);
399         /* missing cache */
400         if (missing_cache_init() == -1) {
401                 *error = g_strdup(_("Failed to load missing items cache"));
402                 return -1;
403         }
404         debug_print("Libravatar plugin loaded\n");
405
406         return 0;
407 }
408
409 /**
410  * Destructor for the plugin.
411  * Unregister the callback function and frees matcher.
412  *
413  * @return Always TRUE.
414  */
415 gboolean plugin_done(void)
416 {
417         if (render_hook_id != -1) {
418                 hooks_unregister_hook(AVATAR_IMAGE_RENDER_HOOKLIST,
419                                       render_hook_id);
420                 render_hook_id = -1;
421         }
422         if (update_hook_id != -1) {
423                 hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST,
424                                       update_hook_id);
425                 update_hook_id = -1;
426         }
427         libravatar_prefs_done();
428         missing_cache_done();
429         if (cache_dir != NULL)
430                 g_free(cache_dir);
431         debug_print("Libravatar plugin unloaded\n");
432
433         return TRUE;
434 }
435
436 /**
437  * Get the name of the plugin.
438  *
439  * @return The plugin's name, maybe translated.
440  */
441 const gchar *plugin_name(void)
442 {
443         return _("Libravatar");
444 }
445
446 /**
447  * Get the description of the plugin.
448  *
449  * @return The plugin's description, maybe translated.
450  */
451 const gchar *plugin_desc(void)
452 {
453         return _("Display libravatar profiles' images for mail messages. More\n"
454                  "info about libravatar at http://www.libravatar.org/. If you have\n"
455                  "a gravatar.com profile but not a libravatar one, those will also\n"
456                  "be retrieved (when redirections are allowed in plugin config).\n"
457                  "Plugin config page it's available from main window at:\n"
458                  "/Configuration/Preferences/Plugins/Libravatar.\n\n"
459                  "This plugin uses libcurl to retrieve images, so if you're behind a\n"
460                  "proxy please refer to curl(1) manpage for details on 'http_proxy'\n"
461                  "configuration. More details about this and others on README file.\n\n"
462                  "Feedback to <ricardo@mones.org> is welcome.\n");
463 }
464
465 /**
466  * Get the kind of plugin.
467  *
468  * @return The "GTK2" constant.
469  */
470 const gchar *plugin_type(void)
471 {
472         return "GTK2";
473 }
474
475 /**
476  * Get the license acronym the plugin is released under.
477  *
478  * @return The "GPL3+" constant.
479  */
480 const gchar *plugin_licence(void)
481 {
482         return "GPL3+";
483 }
484
485 /**
486  * Get the version of the plugin.
487  *
488  * @return The current version string.
489  */
490 const gchar *plugin_version(void)
491 {
492         return VERSION;
493 }
494
495 /**
496  * Get the features implemented by the plugin.
497  *
498  * @return A constant PluginFeature structure with the features.
499  */
500 struct PluginFeature *plugin_provides(void)
501 {
502         static struct PluginFeature features[] =
503                 { {PLUGIN_OTHER, N_("Libravatar")},
504                   {PLUGIN_NOTHING, NULL}};
505
506         return features;
507 }
508