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