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