]> git.street.me.uk Git - andy/viking.git/blob - src/osm-traces.c
Show distance axis grids on distance graphs.
[andy/viking.git] / src / osm-traces.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2007, Guilhem Bonnefille <guilhem.bonnefille@gmail.com>
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 2 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, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <time.h>
29
30 #include <curl/curl.h>
31 #include <curl/easy.h>
32
33 #include <glib.h>
34 #include <glib/gstdio.h>
35 #include <glib/gi18n.h>
36
37 #include "viking.h"
38 #include "viktrwlayer.h"
39 #include "osm-traces.h"
40 #include "gpx.h"
41 #include "background.h"
42 #include "preferences.h"
43
44 /* params will be osm_traces.username, osm_traces.password */
45 /* we have to make sure these don't collide. */
46 #define VIKING_OSM_TRACES_PARAMS_GROUP_KEY "osm_traces"
47 #define VIKING_OSM_TRACES_PARAMS_NAMESPACE "osm_traces."
48
49 #define VIK_SETTINGS_OSM_TRACE_VIS "osm_trace_visibility"
50 static gint last_active = -1;
51
52 /**
53  * Login to use for OSM uploading.
54  */
55 static gchar *osm_user = NULL;
56
57 /**
58  * Password to use for OSM uploading.
59  */
60 static gchar *osm_password = NULL;
61
62 /**
63  * Mutex to protect auth. token
64  */
65 static GMutex *login_mutex = NULL;
66
67 /**
68  * Different type of trace visibility.
69  */
70 typedef struct _OsmTraceVis_t {
71         const gchar *combostr;
72         const gchar *apistr;
73 } OsmTraceVis_t;
74
75 static const OsmTraceVis_t OsmTraceVis[] = {
76         { N_("Identifiable (public w/ timestamps)"),    "identifiable" },
77         { N_("Trackable (private w/ timestamps)"),      "trackable" },
78         { N_("Public"),                                 "public" },
79         { N_("Private"),                                "private" },
80         { NULL, NULL },
81 };
82
83 /**
84  * Struct hosting needed info.
85  */
86 typedef struct _OsmTracesInfo {
87   gchar *name;
88   gchar *description;
89   gchar *tags;
90   gboolean anonymize_times; // ATM only available on a single track.
91   const OsmTraceVis_t *vistype;
92   VikTrwLayer *vtl;
93   VikTrack *trk;
94 } OsmTracesInfo;
95
96 static VikLayerParam prefs[] = {
97   { VIK_LAYER_NUM_TYPES, VIKING_OSM_TRACES_PARAMS_NAMESPACE "username", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("OSM username:"), VIK_LAYER_WIDGET_ENTRY, NULL, NULL, NULL, NULL, NULL, NULL },
98   { VIK_LAYER_NUM_TYPES, VIKING_OSM_TRACES_PARAMS_NAMESPACE "password", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("OSM password:"), VIK_LAYER_WIDGET_PASSWORD, NULL, NULL, NULL, NULL, NULL, NULL },
99 };
100
101 /**
102  * Free an OsmTracesInfo struct.
103  */
104 static void oti_free(OsmTracesInfo *oti)
105 {
106   if (oti) {
107     /* Fields have been g_strdup'ed */
108     g_free(oti->name); oti->name = NULL;
109     g_free(oti->description); oti->description = NULL;
110     g_free(oti->tags); oti->tags = NULL;
111     
112     g_object_unref(oti->vtl); oti->vtl = NULL;
113   }
114   /* Main struct has been g_malloc'ed */
115   g_free(oti);
116 }
117
118 static const gchar *get_default_user()
119 {
120   const gchar *default_user = NULL;
121
122   /* Retrieve "standard" EMAIL varenv */
123   default_user = g_getenv("EMAIL");
124
125   return default_user;
126 }
127
128 void osm_set_login(const gchar *user, const gchar *password)
129 {
130   /* Allocate mutex */
131   if (login_mutex == NULL)
132   {
133     login_mutex = g_mutex_new();
134   }
135   g_mutex_lock(login_mutex);
136   g_free(osm_user); osm_user = NULL;
137   g_free(osm_password); osm_password = NULL;
138   osm_user        = g_strdup(user);
139   osm_password    = g_strdup(password);
140   g_mutex_unlock(login_mutex);
141 }
142
143 gchar *osm_get_login()
144 {
145   gchar *user_pass = NULL;
146   g_mutex_lock(login_mutex);
147   user_pass = g_strdup_printf("%s:%s", osm_user, osm_password);
148   g_mutex_unlock(login_mutex);
149   return user_pass;
150 }
151
152 /* initialisation */
153 void osm_traces_init () {
154   /* Preferences */
155   a_preferences_register_group ( VIKING_OSM_TRACES_PARAMS_GROUP_KEY, _("OpenStreetMap Traces") );
156
157   VikLayerParamData tmp;
158   tmp.s = "";
159   a_preferences_register(prefs, tmp, VIKING_OSM_TRACES_PARAMS_GROUP_KEY);
160   tmp.s = "";
161   a_preferences_register(prefs+1, tmp, VIKING_OSM_TRACES_PARAMS_GROUP_KEY);
162
163 }
164
165 /*
166  * Upload a file
167  * returns a basic status:
168  *   < 0  : curl error
169  *   == 0 : OK
170  *   > 0  : HTTP error
171   */
172 static gint osm_traces_upload_file(const char *user,
173                                    const char *password,
174                                    const char *file,
175                                    const char *filename,
176                                    const char *description,
177                                    const char *tags,
178                                    const OsmTraceVis_t *vistype)
179 {
180   CURL *curl;
181   CURLcode res;
182   char curl_error_buffer[CURL_ERROR_SIZE];
183   struct curl_slist *headers = NULL;
184   struct curl_httppost *post=NULL;
185   struct curl_httppost *last=NULL;
186
187   char *base_url = "http://www.openstreetmap.org/api/0.6/gpx/create";
188
189   gchar *user_pass = osm_get_login();
190
191   gint result = 0; // Default to it worked!
192
193   g_debug("%s: %s %s %s %s %s %s", __FUNCTION__,
194           user, password, file, filename, description, tags);
195
196   /* Init CURL */
197   curl = curl_easy_init();
198
199   /* Filling the form */
200   curl_formadd(&post, &last,
201                CURLFORM_COPYNAME, "description",
202                CURLFORM_COPYCONTENTS, description, CURLFORM_END);
203   curl_formadd(&post, &last,
204                CURLFORM_COPYNAME, "tags",
205                CURLFORM_COPYCONTENTS, tags, CURLFORM_END);
206   curl_formadd(&post, &last,
207                CURLFORM_COPYNAME, "visibility",
208                CURLFORM_COPYCONTENTS, vistype->apistr, CURLFORM_END);
209   curl_formadd(&post, &last,
210                CURLFORM_COPYNAME, "file",
211                CURLFORM_FILE, file,
212                CURLFORM_FILENAME, filename,
213                CURLFORM_CONTENTTYPE, "text/xml", CURLFORM_END);
214
215   /* Prepare request */
216   /* As explained in http://wiki.openstreetmap.org/index.php/User:LA2 */
217   /* Expect: header seems to produce incompatibilites between curl and httpd */
218   headers = curl_slist_append(headers, "Expect: ");
219   curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
220   curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
221   curl_easy_setopt(curl, CURLOPT_URL, base_url);
222   curl_easy_setopt(curl, CURLOPT_USERPWD, user_pass);
223   curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
224   curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_error_buffer);
225   if (vik_verbose)
226     curl_easy_setopt ( curl, CURLOPT_VERBOSE, 1 );
227
228   /* Execute request */
229   res = curl_easy_perform(curl);
230   if (res == CURLE_OK)
231   {
232     long code;
233     res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
234     if (res == CURLE_OK)
235     {
236       g_debug("received valid curl response: %ld", code);
237       if (code != 200) {
238         g_warning(_("failed to upload data: HTTP response is %ld"), code);
239         result = code;
240       }
241     }
242     else {
243       g_critical(_("curl_easy_getinfo failed: %d"), res);
244       result = -1;
245     }
246   }
247   else {
248     g_warning(_("curl request failed: %s"), curl_error_buffer);
249     result = -2;
250   }
251
252   /* Memory */
253   g_free(user_pass); user_pass = NULL;
254   
255   curl_formfree(post);
256   curl_easy_cleanup(curl);
257   return result;
258 }
259
260 /**
261  * uploading function executed by the background" thread
262  */
263 static void osm_traces_upload_thread ( OsmTracesInfo *oti, gpointer threaddata )
264 {
265   /* Due to OSM limits, we have to enforce ele and time fields
266    also don't upload invisible tracks */
267   static GpxWritingOptions options = { TRUE, TRUE, FALSE, FALSE };
268   FILE *file = NULL;
269   gchar *filename = NULL;
270   int fd;
271   GError *error = NULL;
272   int ret;
273
274   g_assert(oti != NULL);
275
276   /* Opening temporary file */
277   fd = g_file_open_tmp("viking_osm_upload_XXXXXX.gpx", &filename, &error);
278   if (fd < 0) {
279     g_error(_("failed to open temporary file: %s"), strerror(errno));
280     return;
281   }
282   g_clear_error(&error);
283   g_debug("%s: temporary file = %s", __FUNCTION__, filename);
284
285   /* Creating FILE* */
286   file = fdopen(fd, "w");
287
288   /* writing gpx file */
289   if (oti->trk != NULL)
290   {
291     /* Upload only the selected track */
292     if ( oti->anonymize_times )
293     {
294       VikTrack *trk = vik_track_copy(oti->trk, TRUE);
295       vik_track_anonymize_times(trk);
296       a_gpx_write_track_file(trk, file, &options);
297       vik_track_free(trk);
298     }
299     else
300       a_gpx_write_track_file(oti->trk, file, &options);
301   }
302   else
303   {
304     /* Upload the whole VikTrwLayer */
305     a_gpx_write_file(oti->vtl, file, &options);
306   }
307   
308   /* We can close the file */
309   /* This also close the associated fd */
310   fclose(file);
311   file = NULL;
312
313   /* finally, upload it */
314   gint ans = osm_traces_upload_file(osm_user, osm_password, filename,
315                    oti->name, oti->description, oti->tags, oti->vistype);
316
317   //
318   // Show result in statusbar or failure in dialog for user feedback
319   //
320
321   // Get current time to put into message to show when result was generated
322   //  since need to show difference between operations (when displayed on statusbar)
323   // NB If on dialog then don't need time.
324   time_t timenow;
325   struct tm* timeinfo;
326   time ( &timenow );
327   timeinfo = localtime ( &timenow );
328   gchar timestr[80];
329   // Compact time only - as days/date isn't very useful here
330   strftime ( timestr, sizeof(timestr), "%X)", timeinfo );
331
332   //
333   // Test to see if window it was invoked on is still valid
334   // Not sure if this test really works! (i.e. if the window was closed in the mean time)
335   //
336   if ( IS_VIK_WINDOW ((VikWindow *)VIK_GTK_WINDOW_FROM_LAYER(oti->vtl)) ) {
337     gchar* msg;
338     if ( ans == 0 ) {
339       // Success
340       msg = g_strdup_printf ( "%s (@%s)", _("Uploaded to OSM"), timestr );
341     }
342     // Use UPPER CASE for bad news :(
343     else if ( ans < 0 ) {
344       msg = g_strdup_printf ( "%s (@%s)", _("FAILED TO UPLOAD DATA TO OSM - CURL PROBLEM"), timestr );
345     }
346     else {
347       msg = g_strdup_printf ( "%s : %s %d (@%s)", _("FAILED TO UPLOAD DATA TO OSM"), _("HTTP response code"), ans, timestr );
348     }
349     vik_window_statusbar_update ( (VikWindow*)VIK_GTK_WINDOW_FROM_LAYER(oti->vtl), msg, VIK_STATUSBAR_INFO );
350     g_free (msg);
351   }
352   /* Removing temporary file */
353   ret = g_unlink(filename);
354   if (ret != 0) {
355     g_critical(_("failed to unlink temporary file: %s"), strerror(errno));
356   }
357 }
358
359 /**
360  *
361  */
362 void osm_login_widgets (GtkWidget *user_entry, GtkWidget *password_entry)
363 {
364   if (!user_entry || !password_entry)
365     return;
366
367   const gchar *default_user = get_default_user();
368   const gchar *pref_user = a_preferences_get(VIKING_OSM_TRACES_PARAMS_NAMESPACE "username")->s;
369   const gchar *pref_password = a_preferences_get(VIKING_OSM_TRACES_PARAMS_NAMESPACE "password")->s;
370
371   if (osm_user != NULL && osm_user[0] != '\0')
372     gtk_entry_set_text(GTK_ENTRY(user_entry), osm_user);
373   else if (pref_user != NULL && pref_user[0] != '\0')
374     gtk_entry_set_text(GTK_ENTRY(user_entry), pref_user);
375   else if (default_user != NULL)
376     gtk_entry_set_text(GTK_ENTRY(user_entry), default_user);
377
378   if (osm_password != NULL && osm_password[0] != '\0')
379     gtk_entry_set_text(GTK_ENTRY(password_entry), osm_password);
380   else if (pref_password != NULL)
381     gtk_entry_set_text(GTK_ENTRY(password_entry), pref_password);
382   /* This is a password -> invisible */
383   gtk_entry_set_visibility(GTK_ENTRY(password_entry), FALSE);
384 }
385
386 /**
387  * Uploading a VikTrwLayer
388  *
389  * @param vtl VikTrwLayer
390  * @param trk if not null, the track to upload
391  */
392 void osm_traces_upload_viktrwlayer ( VikTrwLayer *vtl, VikTrack *trk )
393 {
394   GtkWidget *dia = gtk_dialog_new_with_buttons (_("OSM upload"),
395                                                  VIK_GTK_WINDOW_FROM_LAYER(vtl),
396                                                  GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
397                                                  GTK_STOCK_CANCEL,
398                                                  GTK_RESPONSE_REJECT,
399                                                  GTK_STOCK_OK,
400                                                  GTK_RESPONSE_ACCEPT,
401                                                  NULL);
402
403   const gchar *name = NULL;
404   GtkWidget *user_label, *user_entry;
405   GtkWidget *password_label, *password_entry;
406   GtkWidget *name_label, *name_entry;
407   GtkWidget *description_label, *description_entry;
408   GtkWidget *tags_label, *tags_entry;
409   GtkWidget *visibility;
410   GtkWidget *anonymize_checkbutton = NULL;
411   const OsmTraceVis_t *vis_t;
412
413   user_label = gtk_label_new(_("Email:"));
414   user_entry = gtk_entry_new();
415   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), user_label, FALSE, FALSE, 0);
416   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), user_entry, FALSE, FALSE, 0);
417   gtk_widget_set_tooltip_markup(GTK_WIDGET(user_entry),
418                         _("The email used as login\n"
419                         "<small>Enter the email you use to login into www.openstreetmap.org.</small>"));
420
421   password_label = gtk_label_new(_("Password:"));
422   password_entry = gtk_entry_new();
423   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), password_label, FALSE, FALSE, 0);
424   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), password_entry, FALSE, FALSE, 0);
425   gtk_widget_set_tooltip_markup(GTK_WIDGET(password_entry),
426                         _("The password used to login\n"
427                         "<small>Enter the password you use to login into www.openstreetmap.org.</small>"));
428
429   osm_login_widgets ( user_entry, password_entry );
430
431   name_label = gtk_label_new(_("File's name:"));
432   name_entry = gtk_entry_new();
433   if (trk != NULL)
434     name = trk->name;
435   else
436     name = vik_layer_get_name(VIK_LAYER(vtl));
437   gtk_entry_set_text(GTK_ENTRY(name_entry), name);
438   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), name_label, FALSE, FALSE, 0);
439   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), name_entry, FALSE, FALSE, 0);
440   gtk_widget_set_tooltip_markup(GTK_WIDGET(name_entry),
441                         _("The name of the file on OSM\n"
442                         "<small>This is the name of the file created on the server."
443                         "This is not the name of the local file.</small>"));
444
445   description_label = gtk_label_new(_("Description:"));
446   description_entry = gtk_entry_new();
447   const gchar *description = NULL;
448   if (trk != NULL)
449     description = trk->description;
450   else {
451     VikTRWMetadata *md = vik_trw_layer_get_metadata (vtl);
452     description = md ? md->description : NULL;
453   }
454   if (description)
455     gtk_entry_set_text(GTK_ENTRY(description_entry), description);
456   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), description_label, FALSE, FALSE, 0);
457   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), description_entry, FALSE, FALSE, 0);
458   gtk_widget_set_tooltip_text(GTK_WIDGET(description_entry),
459                         _("The description of the trace"));
460
461   if (trk != NULL) {
462     GtkWidget *label = gtk_label_new(_("Anonymize Times:"));
463     anonymize_checkbutton = gtk_check_button_new ();
464     gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), label, FALSE, FALSE, 0);
465     gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), anonymize_checkbutton, FALSE, FALSE, 0);
466     gtk_widget_set_tooltip_text(GTK_WIDGET(anonymize_checkbutton),
467                                 _("Anonymize times of the trace.\n"
468                                   "<small>You may choose to make the trace identifiable, yet mask the actual real time values</small>"));
469   }
470
471   tags_label = gtk_label_new(_("Tags:"));
472   tags_entry = gtk_entry_new();
473   VikTRWMetadata *md = vik_trw_layer_get_metadata (vtl);
474   if (md->keywords)
475     gtk_entry_set_text(GTK_ENTRY(tags_entry), md->keywords);
476   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), tags_label, FALSE, FALSE, 0);
477   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), tags_entry, FALSE, FALSE, 0);
478   gtk_widget_set_tooltip_text(GTK_WIDGET(tags_entry),
479                         _("The tags associated to the trace"));
480
481   visibility = vik_combo_box_text_new();
482   for (vis_t = OsmTraceVis; vis_t->combostr != NULL; vis_t++)
483     vik_combo_box_text_append (visibility, vis_t->combostr);
484
485   // Set identifiable by default or use the settings for the value
486   if ( last_active < 0 ) {
487     gint find_entry = -1;
488     gint wanted_entry = -1;
489     gchar *vis = NULL;
490     if ( a_settings_get_string ( VIK_SETTINGS_OSM_TRACE_VIS, &vis ) ) {
491       // Use setting
492       if ( vis ) {
493         for (vis_t = OsmTraceVis; vis_t->apistr != NULL; vis_t++) {
494           find_entry++;
495           if (!strcmp(vis, vis_t->apistr)) {
496             wanted_entry = find_entry;
497           }
498         }
499       }
500       // If not found set it to the first entry, otherwise use the entry
501       last_active = ( wanted_entry < 0 ) ? 0 : wanted_entry;
502     }
503     else
504       last_active = 0;
505   }
506   gtk_combo_box_set_active(GTK_COMBO_BOX(visibility), last_active);
507   gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dia))), GTK_WIDGET(visibility), FALSE, FALSE, 0);
508
509   /* User should think about it first... */
510   gtk_dialog_set_default_response ( GTK_DIALOG(dia), GTK_RESPONSE_REJECT );
511
512   gtk_widget_show_all ( dia );
513   gtk_widget_grab_focus ( description_entry );
514
515   if ( gtk_dialog_run ( GTK_DIALOG(dia) ) == GTK_RESPONSE_ACCEPT )
516   {
517     gchar *title = NULL;
518
519     /* overwrite authentication info */
520     osm_set_login(gtk_entry_get_text(GTK_ENTRY(user_entry)),
521                   gtk_entry_get_text(GTK_ENTRY(password_entry)));
522
523     /* Storing data for the future thread */
524     OsmTracesInfo *info = g_malloc(sizeof(OsmTracesInfo));
525     info->name        = g_strdup(gtk_entry_get_text(GTK_ENTRY(name_entry)));
526     info->description = g_strdup(gtk_entry_get_text(GTK_ENTRY(description_entry)));
527     /* TODO Normalize tags: they will be used as URL part */
528     info->tags        = g_strdup(gtk_entry_get_text(GTK_ENTRY(tags_entry)));
529     info->vistype     = &OsmTraceVis[gtk_combo_box_get_active(GTK_COMBO_BOX(visibility))];
530     info->vtl         = VIK_TRW_LAYER(g_object_ref(vtl));
531     info->trk         = trk;
532     if (trk != NULL && anonymize_checkbutton != NULL )
533       info->anonymize_times = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(anonymize_checkbutton));
534     else
535       info->anonymize_times = FALSE;
536
537     // Save visibility value for default reuse
538     last_active = gtk_combo_box_get_active(GTK_COMBO_BOX(visibility));
539     a_settings_set_string ( VIK_SETTINGS_OSM_TRACE_VIS, OsmTraceVis[last_active].apistr );
540
541     title = g_strdup_printf(_("Uploading %s to OSM"), info->name);
542
543     /* launch the thread */
544     a_background_thread(VIK_GTK_WINDOW_FROM_LAYER(vtl),          /* parent window */
545                         title,                                   /* description string */
546                         (vik_thr_func) osm_traces_upload_thread, /* function to call within thread */
547                         info,                                    /* pass along data */
548                         (vik_thr_free_func) oti_free,            /* function to free pass along data */
549                         (vik_thr_free_func) NULL,
550                         1 );
551     g_free ( title ); title = NULL;
552   }
553   gtk_widget_destroy ( dia );
554 }