Debian Codegraph @

extensions/openstreetmap/openstreetmap.py

raw
1 import os, stat
2 import sys
3 import logging
4 from gi.repository import Gtk
5
6 import string
7 from lxml import etree
8
9 import httplib, httplib2
10 import urllib2
11 import mimetools, mimetypes
12 from json import dumps, loads # for deserializing JSON data form javascript
13
14 from pytrainer.extensions.mapviewer import MapViewer
15 from pytrainer.extensions.osm import Osm
16 from pytrainer.lib.localization import gtk_str
17
18 class openstreetmap:
19 def __init__(self, parent = None, pytrainer_main = None, conf_dir = None, options = None):
20 self.parent = parent
21 self.pytrainer_main = pytrainer_main
22 self.options = options
23 self.conf_dir = conf_dir
24 self.description = " "
25 self.tags = ""
26 self.visibility = "private"
27 self.mozTitle="" # Keeps embedded mozilla document title while displaying map for private area selection
28 self.privBounds=[] # Bounds of areas to be anonymized
29
30 def run(self, id, activity=None): #TODO Convert to use activity...
31 logging.debug(">>")
32 try:
33 uri = "http://api.openstreetmap.org/api/0.6/gpx/create" #URI for uploading traces to OSM
34 if 'username' not in self.options or self.options['username'] == "" or 'password' not in self.options or self.options['password'] == "":
35 logging.error("Must have username and password configured")
36 raise Exception("Must have username and password configured")
37 username = self.options['username']
38 password = self.options['password']
39 gpx_file = "%s/gpx/%s.gpx" % (self.conf_dir, id)
40 if not os.path.isfile(gpx_file):
41 raise Exception(str(gps_file) + ' File not found')
42 #GPX file is ok and found, so open it
43 logging.debug("GPX file: %s found, size: %d" % (gpx_file, os.path.getsize(gpx_file)))
44 f = open(gpx_file, 'r')
45 file_contents = f.read()
46 #TODO Fix to use etree functionality.....
47 if file_contents.find("<?xml version='1.0' encoding='ASCII'?>") != -1:
48 logging.debug("GPX file: %s has ASCII encoding - updating to UTF-8 for OSM support" % gpx_file)
49 f.close() #Close readonly file
50 f = open(gpx_file, 'w') #and open file for writing
51 file_contents = file_contents.replace("<?xml version='1.0' encoding='ASCII'?>","<?xml version='1.0' encoding='UTF-8'?>", 1)
52 f.write(file_contents) #Write new content
53 f.close() #Close
54 f = open(gpx_file, 'r') #Reopen in readonly mode
55 #Get extra info from user
56 response=self.display_options_window()
57 if not response==Gtk.ResponseType.ACCEPT:
58 f.close()
59 logging.debug("User abort")
60 return
61 if self.makeanon:
62 logging.debug("User requested anonymizing of GPX data")
63 f.close() #Close standard gpxfile
64 gpx_file = self.make_gpx_private(gpx_file)
65 f = open(gpx_file, 'r') #Open anonymous gpxfile in readonly mode
66 fields = (("description",self.description), ("tags",self.tags), ("visibility",self.visibility))
67 logging.debug("Added fields: %s" % str(fields))
68 #Multipart encode the request
69 boundary, body = self.multipart_encode(fields=fields, files=(("file", f),))
70 content_type = 'multipart/form-data; boundary=%s' % boundary
71 #Finished with the file so close it
72 f.close()
73 #Add the http headers to the request
74 h = httplib2.Http()
75 headers = {
76 'Content-Type': content_type
77 }
78 #Add basic authentication credentials to the request
79 h.add_credentials(username, password)
80 #Show user something is happening
81 msg = _("Posting GPX trace to Openstreetmap\n\nPlease wait this could take several minutes")
82 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO, Gtk.ButtonsType.NONE, msg)
83 md.set_title(_("Openstreetmap Extension Processing"))
84 md.set_modal(True)
85 md.show()
86 while Gtk.events_pending(): # This allows the GUI to update
87 Gtk.main_iteration() # before completion of this entire action
88 logging.debug("before request posting")
89 #POST request to OSM
90 res, content = h.request(uri, 'POST', body=body, headers=headers)
91 logging.debug("after request posting")
92 logging.debug("Got response status: %s, reason: %s, content: %s" % (res.status, res.reason, content))
93 if res.reason == 'OK':
94 res_msg = "Successfully posted to OSM.\nYou should get an email with the outcome of the upload soon\n\nTrace id is %s" % content
95 else:
96 res_msg = "Some error occured\nGot a status %s, reason %s\nContent was: %s" % (res.status, res.reason, content)
97 #Close 'Please wait' dialog
98 md.destroy()
99 #Show the user the result
100 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, res_msg)
101 md.set_title(_("Openstreetmap Extension Upload Complete"))
102 md.set_modal(False)
103 md.run()
104 md.destroy()
105 except Exception as e:
106 msg = _("Error while uploading file to OSM: " + str(e))
107 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, msg)
108 md.set_title(_("Openstreetmap Extension Error"))
109 md.run()
110 md.destroy()
111 return
112 finally:
113 logging.debug("<<")
114
115 def display_options_window(self):
116 self.prefwindow = Gtk.Dialog(title=_("Please add any additional information for this upload"), parent=None, flags=Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT, Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT))
117 self.prefwindow.set_modal(False)
118 table = Gtk.Table(1,3)
119 self.entryList = []
120 #Add description
121 label = Gtk.Label(label="<b>Description</b>")
122 label.set_use_markup(True)
123 entry = Gtk.Entry()
124 self.entryList.append(entry)
125 table.attach(label,0,1,0,1)
126 table.attach(entry,1,2,0,1)
127 #Add tags
128 label = Gtk.Label(label="<b>Tags</b>")
129 label.set_use_markup(True)
130 entry = Gtk.Entry()
131 self.entryList.append(entry)
132 table.attach(label,0,1,1,2)
133 table.attach(entry,1,2,1,2)
134 #Add visibility
135 label = Gtk.Label(label="<b>Visibility</b>")
136 label.set_use_markup(True)
137 combobox = Gtk.ComboBoxText()
138 combobox.append_text("private")
139 combobox.append_text("public")
140 combobox.append_text("trackable")
141 combobox.append_text("identifiable")
142 combobox.set_active(0)
143 table.attach(combobox,1,2,2,3)
144 self.entryList.append(combobox)
145 table.attach(label,0,1,2,3)
146 #Add anonymize GPX option
147 label = Gtk.Label(label="<b>Anonymize GPX Data</b>")
148 label.set_use_markup(True)
149 table.attach(label,0,1,3,4)
150 checkbutton = Gtk.CheckButton()
151 table.attach(checkbutton,1,2,3,4)
152 self.entryList.append(checkbutton)
153 #Add anon area selection button
154 button = Gtk.Button("Area selection")
155 button.connect("clicked",self.areaSelect)
156 table.attach(button,1,2,4,5)
157 self.entryList.append(button)
158 #Build dialog and show
159 self.prefwindow.vbox.pack_start(table, True, True, 0)
160 self.prefwindow.show_all()
161 self.prefwindow.connect("response", self.on_options_ok_clicked)
162 response=self.prefwindow.run()
163 self.prefwindow.destroy()
164 return response
165
166 def on_options_ok_clicked(self, widget, response_id):
167 if not response_id == Gtk.ResponseType.ACCEPT:
168 return response_id
169 self.description = gtk_str(self.entryList[0].get_text())
170 if self.description == "":
171 logging.debug("A description is required - setting to default")
172 self.description = "Uploaded from pytrainer"
173 self.tags = gtk_str(self.entryList[1].get_text())
174 self.visibility = gtk_str(self.entryList[2].get_active_text())
175 self.makeanon = self.entryList[3].get_active()
176 logging.debug("Description: %s, tags: %s, visibility: %s, makeanon: %s" % ( self.description, self.tags, self.visibility, self.makeanon) )
177
178 def areaSelect(self,dc):
179 """
180 Open a window with OSM map so user could select his private/anonymized area -
181 all GPX dots in this area will be removed before uploading to OSM
182 """
183 try:
184 wTree = Gtk.glade.XML(self.pytrainer_main.data_path+"extensions/openstreetmap/OSM_AnonSelection.glade")
185 self.privAreaWindow = wTree.get_widget("OSM_AnonSelection")
186 dic = {
187 "on_buttonOk_clicked" : self.privArea_Ok,
188 "on_buttonCancel_clicked" : self.privArea_Cancel
189 }
190 wTree.signal_autoconnect( dic )
191 mapviewer = MapViewer(self.pytrainer_main.data_path, pytrainer_main=self.pytrainer_main, box=wTree.get_widget("mapBox"))
192 json=None
193 if 'privPolygon' in self.options:
194 json=self.options['privPolygon']
195 htmlfile = Osm(data_path=self.pytrainer_main.data_path, waypoint=json, pytrainer_main=self.pytrainer_main).selectArea()
196 mapviewer.display_map(htmlfile=htmlfile)
197 mapviewer.moz.connect('title', self.parseTitle)
198 self.privAreaWindow.show()
199
200 except Exception as e:
201 msg = "Could not init map selection screen, Error: " + str(e)
202 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, msg)
203 md.set_title(_("Error"))
204 md.run()
205 md.destroy()
206 return
207
208 def parseTitle(self, moz):
209 "Event fired when document title was changed -> meaning polygon was changed"
210 if moz.get_title() != "":
211 self.mozTitle=str(moz.get_title())
212
213 def privArea_Cancel(self,button):
214 "Event fired when cancel button was pressed"
215 self.privAreaWindow.destroy()
216
217 def privArea_Ok(self,button):
218 "Event fired when ok button was pressed"
219 logging.debug(">> privArea_Ok")
220 # save new private area polygon if changed
221 if self.mozTitle=="":
222 return
223 # try parsing JSON
224 try:
225 # verify json is correct by deserializing and serializing it
226 polygonString=dumps(loads(self.mozTitle))
227 # try saving
228 extensionDir = self.pytrainer_main.data_path + "/extensions" + "/openstreetmap"
229 if not os.path.isdir(extensionDir):
230 loggin.error(str(e))
231 raise Exception("Could not find extension path: " + str(extensionDir))
232 # save new options
233 self.options['privPolygon'] = polygonString
234 # convert dictionary to a lists set
235 savedOptions = []
236 for key in self.options:
237 savedOptions.append((key,self.options[key]))
238 # write new xml config file
239 self.parent.setExtensionConfParams(extensionDir, savedOptions)
240 except Exception as e:
241 logging.error(str(e))
242 msg = _(str(e))
243 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, msg)
244 md.set_title(_("Error while saving extension configuration"))
245 md.run()
246 md.destroy()
247 finally:
248 self.privAreaWindow.destroy()
249
250 def multipart_encode(self, fields, files, boundary = None, buffer = None):
251 '''
252 Multipart encode data for posting
253 from examples at from http://odin.himinbi.org/MultipartPostHandler.py & http://bitworking.org/projects/httplib2/doc/html/libhttplib2.html
254 '''
255 if boundary is None:
256 boundary = mimetools.choose_boundary()
257 if buffer is None:
258 buffer = ''
259 for (key, value) in fields:
260 buffer += '--%s\r\n' % boundary
261 buffer += 'Content-Disposition: form-data; name="%s"' % key
262 buffer += '\r\n\r\n' + value + '\r\n'
263 for (key, fd) in files:
264 file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
265 filename = os.path.basename(fd.name)
266 contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
267 buffer += '--%s\r\n' % boundary
268 buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
269 buffer += 'Content-Type: %s\r\n' % contenttype
270 # buffer += 'Content-Length: %s\r\n' % file_size
271 fd.seek(0)
272 buffer += '\r\n' + fd.read() + '\r\n'
273 buffer += '--%s--\r\n\r\n' % boundary
274 return boundary, buffer
275
276 def make_gpx_private(self, gpx_file=None):
277 '''
278 wipes out private data from gpx files
279 converts laps to waypoints
280 '''
281 logging.debug(">>")
282 if gpx_file is None:
283 return None
284
285 filen = os.path.basename(gpx_file)
286 tmpdir = self.pytrainer_main.profile.tmpdir
287 anon_gpx_file = "%s/%s" % (tmpdir, filen)
288
289 # get saved private area polygon
290 pP=loads(self.options['privPolygon'])
291 pP=pP['geometry']['coordinates'][0]
292 # converts polygon's 2D matrix into a vector of just the lats or lons
293 vector = lambda lonLat: [pP[i][lonLat] for i in range(len(pP))] # 0:lon, 1:lat
294 # try reading private area's bounds, stored as [lon,lat]
295 NE_LAT = max([pP[i][1] for i in range(len(pP))])
296 NE_LON = max([pP[i][0] for i in range(len(pP))])
297 SW_LAT = min([pP[i][1] for i in range(len(pP))])
298 SW_LON = min([pP[i][0] for i in range(len(pP))])
299 logging.info("Anonymizing Area: NE:%f,%f -> SW: %f,%f" % (NE_LON, NE_LAT, SW_LON, SW_LAT))
300
301 # Config parameters, not used yet
302 FILTER_BOX = True
303 ERASE_TIME = True
304 LAP_TO_WAYPOINT = True
305
306 tree = etree.parse(gpx_file)
307 _xmlns = tree.getroot().nsmap[None]
308 _trkpt_path = '{%s}trk/{%s}trkseg/{%s}trkpt' % (_xmlns, _xmlns, _xmlns)
309 # namespace of gpx files
310 NS = dict(ns='http://www.topografix.com/GPX/1/1')
311
312 myroot = tree.getroot()
313 gpxdataNS = string.Template(\
314 ".//{http://www.cluetrust.com/XML/GPXDATA/1/0}$tag")
315 lapTag = gpxdataNS.substitute(tag="lap")
316 endPointTag = gpxdataNS.substitute(tag="endPoint")
317 triggerTag = gpxdataNS.substitute(tag="trigger")
318 laps = tree.findall(lapTag)
319
320 mygpx = tree.find('gpx')
321
322 for lap in laps:
323 trigger = lap.find(triggerTag)
324 # Watch out for manually triggered laps
325 if trigger.text == 'manual':
326 endPoint = lap.find(endPointTag)
327 lat = endPoint.get("lat")
328 lon = endPoint.get("lon")
329 # Create waypt if not in home box
330 try:
331 if not ((SW_LAT < float(lat) < NE_LAT) and (SW_LON < float(lon) < NE_LON)):
332 etree.SubElement(myroot, 'wpt', attrib= {'lat':lat, 'lon':lon})
333 except:
334 pass
335 etree.strip_attributes(myroot, 'creator')
336
337 # Wipe out home box
338 for trkpt in tree.findall(_trkpt_path):
339 lat = float(trkpt.attrib['lat'])
340 lon = float(trkpt.attrib['lon'])
341 if (lat < NE_LAT) & (lon < NE_LON) & (lat > SW_LAT) & (lon > SW_LON):
342 par = trkpt.getparent()
343 par.remove(trkpt)
344
345 time = tree.xpath('//ns:trkpt/ns:time', namespaces=NS)
346 for i in time:
347 i.text = '1970-01-01T00:00:00+00:00'
348 # osm regards <time> as mandatory. gnaa.
349
350 ext = tree.xpath('//ns:gpx/ns:extensions', namespaces=NS)
351 for i in ext:
352 par = i.getparent()
353 par.remove(i)
354 meta = tree.xpath('//ns:gpx/ns:metadata', namespaces=NS)
355 for i in meta:
356 par = i.getparent()
357 par.remove(i)
358 ele = tree.xpath('//ns:trkpt/ns:ele', namespaces=NS)
359 for i in ele:
360 par = i.getparent()
361 par.remove(i)
362
363 # test schema on cleaned xml-tree
364 # gpx.xsd from http://www.topografix.com/gpx.asp
365
366 #xmlschema = etree.XMLSchema(etree.parse('gpx.xsd'))
367 #xmlschema.validate(tree)
368
369 # write new gpx file
370 tree.write(anon_gpx_file, pretty_print=False, xml_declaration=True, encoding='UTF-8')
371 logging.debug("<<")
372 return anon_gpx_file
373