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