]> git.street.me.uk Git - andy/viking.git/blob - src/osm-traces.c
Fix typo
[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
29 #include <curl/curl.h>
30 #include <curl/easy.h>
31
32 #include <glib.h>
33 #include <glib/gstdio.h>
34 #include <glib/gi18n.h>
35
36 #include "viking.h"
37 #include "viktrwlayer.h"
38 #include "osm-traces.h"
39 #include "gpx.h"
40 #include "background.h"
41 #include "preferences.h"
42
43 /* params will be osm_traces.username, osm_traces.password */
44 /* we have to make sure these don't collide. */
45 #define VIKING_OSM_TRACES_PARAMS_GROUP_KEY "osm_traces"
46 #define VIKING_OSM_TRACES_PARAMS_NAMESPACE "osm_traces."
47
48 /**
49  * Login to use for OSM uploading.
50  */
51 static gchar *user = NULL;
52
53 /**
54  * Password to use for OSM uploading.
55  */
56 static gchar *password = NULL;
57
58 /**
59  * Mutex to protect auth. token
60  */
61 static GMutex *login_mutex = NULL;
62
63 /**
64  * Different type of trace visibility.
65  */
66 typedef struct _OsmTraceVis_t {
67         const gchar *combostr;
68         const gchar *apistr;
69 } OsmTraceVis_t;
70
71 static const OsmTraceVis_t OsmTraceVis[] = {
72         { N_("Identifiable (public w/ timestamps)"),    "identifiable" },
73         { N_("Trackable (private w/ timestamps)"),      "trackable" },
74         { N_("Public"),                                 "public" },
75         { N_("Private"),                                "private" },
76         { NULL, NULL },
77 };
78
79 /**
80  * Struct hosting needed info.
81  */
82 typedef struct _OsmTracesInfo {
83   gchar *name;
84   gchar *description;
85   gchar *tags;
86   const OsmTraceVis_t *vistype;
87   VikTrwLayer *vtl;
88   gchar *track_name;
89 } OsmTracesInfo;
90
91 static VikLayerParam prefs[] = {
92   { VIKING_OSM_TRACES_PARAMS_NAMESPACE "username", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("OSM username:"), VIK_LAYER_WIDGET_ENTRY },
93   { VIKING_OSM_TRACES_PARAMS_NAMESPACE "password", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("OSM password:"), VIK_LAYER_WIDGET_PASSWORD },
94 };
95
96 /**
97  * Free an OsmTracesInfo struct.
98  */
99 static void oti_free(OsmTracesInfo *oti)
100 {
101   if (oti) {
102     /* Fields have been g_strdup'ed */
103     g_free(oti->name); oti->name = NULL;
104     g_free(oti->description); oti->description = NULL;
105     g_free(oti->tags); oti->tags = NULL;
106     g_free(oti->track_name); oti->track_name = NULL;
107     
108     g_object_unref(oti->vtl); oti->vtl = NULL;
109   }
110   /* Main struct has been g_malloc'ed */
111   g_free(oti);
112 }
113
114 static const gchar *get_default_user()
115 {
116   const gchar *default_user = NULL;
117
118   /* Retrieve "standard" EMAIL varenv */
119   default_user = g_getenv("EMAIL");
120
121   return default_user;
122 }
123
124 static void set_login(const gchar *user_, const gchar *password_)
125 {
126   /* Allocate mutex */
127   if (login_mutex == NULL)
128   {
129     login_mutex = g_mutex_new();
130   }
131   g_mutex_lock(login_mutex);
132   g_free(user); user = NULL;
133   g_free(password); password = NULL;
134   user        = g_strdup(user_);
135   password    = g_strdup(password_);
136   g_mutex_unlock(login_mutex);
137 }
138
139 static gchar *get_login()
140 {
141   gchar *user_pass = NULL;
142   g_mutex_lock(login_mutex);
143   user_pass = g_strdup_printf("%s:%s", user, password);
144   g_mutex_unlock(login_mutex);
145   return user_pass;
146 }
147
148 /* initialisation */
149 void osm_traces_init () {
150   /* Preferences */
151   a_preferences_register_group ( VIKING_OSM_TRACES_PARAMS_GROUP_KEY, _("OpenStreetMap Traces") );
152
153   VikLayerParamData tmp;
154   tmp.s = "";
155   a_preferences_register(prefs, tmp, VIKING_OSM_TRACES_PARAMS_GROUP_KEY);
156   tmp.s = "";
157   a_preferences_register(prefs+1, tmp, VIKING_OSM_TRACES_PARAMS_GROUP_KEY);
158
159 }
160
161 /*
162  * Upload a file
163  */
164 void osm_traces_upload_file(const char *user,
165                             const char *password,
166                             const char *file,
167                             const char *filename,
168                             const char *description,
169                             const char *tags,
170                             const OsmTraceVis_t *vistype)
171 {
172   CURL *curl;
173   CURLcode res;
174   char curl_error_buffer[CURL_ERROR_SIZE];
175   struct curl_slist *headers = NULL;
176   struct curl_httppost *post=NULL;
177   struct curl_httppost *last=NULL;
178
179   char *base_url = "http://www.openstreetmap.org/api/0.6/gpx/create";
180
181   gchar *user_pass = get_login();
182
183   g_debug("%s: %s %s %s %s %s %s", __FUNCTION__,
184           user, password, file, filename, description, tags);
185
186   /* Init CURL */
187   curl = curl_easy_init();
188
189   /* Filling the form */
190   curl_formadd(&post, &last,
191                CURLFORM_COPYNAME, "description",
192                CURLFORM_COPYCONTENTS, description, CURLFORM_END);
193   curl_formadd(&post, &last,
194                CURLFORM_COPYNAME, "tags",
195                CURLFORM_COPYCONTENTS, tags, CURLFORM_END);
196   curl_formadd(&post, &last,
197                CURLFORM_COPYNAME, "visibility",
198                CURLFORM_COPYCONTENTS, vistype->apistr, CURLFORM_END);
199   curl_formadd(&post, &last,
200                CURLFORM_COPYNAME, "file",
201                CURLFORM_FILE, file,
202                CURLFORM_FILENAME, filename,
203                CURLFORM_CONTENTTYPE, "text/xml", CURLFORM_END);
204
205   /* Prepare request */
206   /* As explained in http://wiki.openstreetmap.org/index.php/User:LA2 */
207   /* Expect: header seems to produce incompatibilites between curl and httpd */
208   headers = curl_slist_append(headers, "Expect: ");
209   curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
210   curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
211   curl_easy_setopt(curl, CURLOPT_URL, base_url);
212   curl_easy_setopt(curl, CURLOPT_USERPWD, user_pass);
213   curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
214   curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_error_buffer);
215   if (vik_verbose)
216     curl_easy_setopt ( curl, CURLOPT_VERBOSE, 1 );
217
218   /* Execute request */
219   res = curl_easy_perform(curl);
220   if (res == CURLE_OK)
221   {
222     long code;
223     res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
224     if (res == CURLE_OK)
225     {
226       g_debug("received valid curl response: %ld", code);
227       if (code != 200)
228         g_warning(_("failed to upload data: HTTP response is %ld"), code);
229     }
230     else
231       g_error(_("curl_easy_getinfo failed: %d"), res);
232   }
233   else
234     {
235       g_warning(_("curl request failed: %s"), curl_error_buffer);
236     }
237
238   /* Memory */
239   g_free(user_pass); user_pass = NULL;
240   
241   curl_formfree(post);
242   curl_easy_cleanup(curl); 
243 }
244
245 /**
246  * uploading function executed by the background" thread
247  */
248 static void osm_traces_upload_thread ( OsmTracesInfo *oti, gpointer threaddata )
249 {
250   /* Due to OSM limits, we have to enforce ele and time fields */
251   static GpxWritingOptions options = { TRUE, TRUE };
252   FILE *file = NULL;
253   gchar *filename = NULL;
254   int fd;
255   GError *error = NULL;
256   int ret;
257
258   g_assert(oti != NULL);
259
260   /* Opening temporary file */
261   fd = g_file_open_tmp("viking_osm_upload_XXXXXX.gpx", &filename, &error);
262   if (fd < 0) {
263     g_error(_("failed to open temporary file: %s"), strerror(errno));
264     return;
265   }
266   g_clear_error(&error);
267   g_debug("%s: temporary file = %s", __FUNCTION__, filename);
268
269   /* Creating FILE* */
270   file = fdopen(fd, "w");
271
272   /* writing gpx file */
273   if (oti->track_name != NULL)
274   {
275     /* Upload only the selected track */
276     VikTrack *track = vik_trw_layer_get_track(oti->vtl, oti->track_name);
277     a_gpx_write_track_file_options(&options, oti->track_name, track, file);
278   }
279   else
280   {
281     /* Upload the whole VikTrwLayer */
282     a_gpx_write_file_options(&options, oti->vtl, file);
283   }
284   
285   /* We can close the file */
286   /* This also close the associated fd */
287   fclose(file);
288   file = NULL;
289
290   /* finally, upload it */
291   osm_traces_upload_file(user, password, filename,
292                          oti->name, oti->description, oti->tags, oti->vistype);
293
294   /* Removing temporary file */
295   ret = g_unlink(filename);
296   if (ret != 0) {
297     g_error(_("failed to unlink temporary file: %s"), strerror(errno));
298   }
299 }
300
301 /**
302  * Uploading a VikTrwLayer
303  *
304  * @param vtl VikTrwLayer
305  * @param track_name if not null, the name of the track to upload
306  */
307 static void osm_traces_upload_viktrwlayer ( VikTrwLayer *vtl, const gchar *track_name )
308 {
309   GtkWidget *dia = gtk_dialog_new_with_buttons (_("OSM upload"),
310                                                  VIK_GTK_WINDOW_FROM_LAYER(vtl),
311                                                  GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
312                                                  GTK_STOCK_CANCEL,
313                                                  GTK_RESPONSE_REJECT,
314                                                  GTK_STOCK_OK,
315                                                  GTK_RESPONSE_ACCEPT,
316                                                  NULL);
317
318   const gchar *default_user = get_default_user();
319   const gchar *pref_user = a_preferences_get(VIKING_OSM_TRACES_PARAMS_NAMESPACE "username")->s;
320   const gchar *pref_password = a_preferences_get(VIKING_OSM_TRACES_PARAMS_NAMESPACE "password")->s;
321   const gchar *name = NULL;
322   GtkWidget *user_label, *user_entry;
323   GtkWidget *password_label, *password_entry;
324   GtkWidget *name_label, *name_entry;
325   GtkWidget *description_label, *description_entry;
326   GtkWidget *tags_label, *tags_entry;
327   GtkComboBox *visibility;
328   const OsmTraceVis_t *vis_t;
329
330   user_label = gtk_label_new(_("Email:"));
331   user_entry = gtk_entry_new();
332   if (user != NULL && user[0] != '\0')
333     gtk_entry_set_text(GTK_ENTRY(user_entry), user);
334   else if (pref_user != NULL && pref_user[0] != '\0')
335     gtk_entry_set_text(GTK_ENTRY(user_entry), pref_user);
336   else if (default_user != NULL)
337     gtk_entry_set_text(GTK_ENTRY(user_entry), default_user);
338   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), user_label, FALSE, FALSE, 0);
339   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), user_entry, FALSE, FALSE, 0);
340   gtk_widget_set_tooltip_markup(GTK_WIDGET(user_entry),
341                         _("The email used as login\n"
342                         "<small>Enter the email you use to login into www.openstreetmap.org.</small>"));
343
344   password_label = gtk_label_new(_("Password:"));
345   password_entry = gtk_entry_new();
346   if (password != NULL && password[0] != '\0')
347     gtk_entry_set_text(GTK_ENTRY(password_entry), password);
348   else if (pref_password != NULL)
349     gtk_entry_set_text(GTK_ENTRY(password_entry), pref_password);
350   /* This is a password -> invisible */
351   gtk_entry_set_visibility(GTK_ENTRY(password_entry), FALSE);
352   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), password_label, FALSE, FALSE, 0);
353   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), password_entry, FALSE, FALSE, 0);
354   gtk_widget_set_tooltip_markup(GTK_WIDGET(password_entry),
355                         _("The password used to login\n"
356                         "<small>Enter the password you use to login into www.openstreetmap.org.</small>"));
357
358   name_label = gtk_label_new(_("File's name:"));
359   name_entry = gtk_entry_new();
360   if (track_name != NULL)
361     name = track_name;
362   else
363     name = vik_layer_get_name(VIK_LAYER(vtl));
364   gtk_entry_set_text(GTK_ENTRY(name_entry), name);
365   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), name_label, FALSE, FALSE, 0);
366   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), name_entry, FALSE, FALSE, 0);
367   gtk_widget_set_tooltip_markup(GTK_WIDGET(name_entry),
368                         _("The name of the file on OSM\n"
369                         "<small>This is the name of the file created on the server."
370                         "This is not the name of the local file.</small>"));
371
372   description_label = gtk_label_new(_("Description:"));
373   description_entry = gtk_entry_new();
374   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), description_label, FALSE, FALSE, 0);
375   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), description_entry, FALSE, FALSE, 0);
376   gtk_widget_set_tooltip_text(GTK_WIDGET(description_entry),
377                         _("The description of the trace"));
378
379   tags_label = gtk_label_new(_("Tags:"));
380   tags_entry = gtk_entry_new();
381   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), tags_label, FALSE, FALSE, 0);
382   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), tags_entry, FALSE, FALSE, 0);
383   gtk_widget_set_tooltip_text(GTK_WIDGET(tags_entry),
384                         _("The tags associated to the trace"));
385
386   visibility = GTK_COMBO_BOX(gtk_combo_box_new_text ());
387   for (vis_t = OsmTraceVis; vis_t->combostr != NULL; vis_t++)
388         gtk_combo_box_append_text(visibility, vis_t->combostr);
389   /* Set identifiable by default */
390   gtk_combo_box_set_active(visibility, 0);
391   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dia)->vbox), GTK_WIDGET(visibility), FALSE, FALSE, 0);
392
393   /* User should think about it first... */
394   gtk_dialog_set_default_response ( GTK_DIALOG(dia), GTK_RESPONSE_REJECT );
395
396   gtk_widget_show_all ( dia );
397   gtk_widget_grab_focus ( description_entry );
398
399   if ( gtk_dialog_run ( GTK_DIALOG(dia) ) == GTK_RESPONSE_ACCEPT )
400   {
401     gchar *title = NULL;
402
403     /* overwrite authentication info */
404     set_login(gtk_entry_get_text(GTK_ENTRY(user_entry)),
405               gtk_entry_get_text(GTK_ENTRY(password_entry)));
406
407     /* Storing data for the future thread */
408     OsmTracesInfo *info = g_malloc(sizeof(OsmTracesInfo));
409     info->name        = g_strdup(gtk_entry_get_text(GTK_ENTRY(name_entry)));
410     info->description = g_strdup(gtk_entry_get_text(GTK_ENTRY(description_entry)));
411     /* TODO Normalize tags: they will be used as URL part */
412     info->tags        = g_strdup(gtk_entry_get_text(GTK_ENTRY(tags_entry)));
413     info->vistype     = &OsmTraceVis[gtk_combo_box_get_active(visibility)];
414     info->vtl         = VIK_TRW_LAYER(g_object_ref(vtl));
415     info->track_name  = (track_name == NULL) ? NULL : g_strdup(track_name);
416
417     title = g_strdup_printf(_("Uploading %s to OSM"), info->name);
418
419     /* launch the thread */
420     a_background_thread(VIK_GTK_WINDOW_FROM_LAYER(vtl),          /* parent window */
421                         title,                                   /* description string */
422                         (vik_thr_func) osm_traces_upload_thread, /* function to call within thread */
423                         info,                                    /* pass along data */
424                         (vik_thr_free_func) oti_free,            /* function to free pass along data */
425                         (vik_thr_free_func) NULL,
426                         1 );
427     g_free ( title ); title = NULL;
428   }
429   gtk_widget_destroy ( dia );
430 }
431
432 /**
433  * Function called by the entry menu of a TrwLayer
434  */
435 void osm_traces_upload_cb ( gpointer layer_and_vlp[2], guint file_type )
436 {
437   osm_traces_upload_viktrwlayer(VIK_TRW_LAYER(layer_and_vlp[0]), NULL);
438 }
439
440 /**
441  * Function called by the entry menu of a single track
442  */
443 void osm_traces_upload_track_cb ( gpointer pass_along[6] )
444 {
445   osm_traces_upload_viktrwlayer(VIK_TRW_LAYER(pass_along[0]), pass_along[3]);
446 }