+def get_osm_list(username,password,year,month):
+
+ url = "https://www.openstreetmap.org/api/0.6/user/gpx_files"
+ passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
+ passman.add_password(None, url, username, password)
+ authhandler = urllib2.HTTPBasicAuthHandler(passman)
+ opener = urllib2.build_opener(authhandler)
+ urllib2.install_opener(opener)
+
+ req = urllib2.urlopen(url)
+ xml = etree.parse(req)
+
+ res=[]
+
+ for gpx_file in xml.getroot():
+ attrib = dict(gpx_file.attrib)
+ timestamp=datetime.fromtimestamp(ParseDateTimeUTC(attrib['timestamp']))
+ id = attrib['id']
+ description=None
+ for descr in gpx_file.iter('description'):
+ description=descr.text
+ sport=None
+ for tag in gpx_file.iter('tag'):
+ sport=tag.text
+ if timestamp.year==year and timestamp.month==month and description=='Run.GPS Track':
+ print id,description,sport,timestamp
+ record={ 'id': id, 'sport': sport }
+ res.append(record)
+
+ return res
+
+def get_osm_gpx(username,password,track_id):
+
+ url = "https://www.openstreetmap.org/api/0.6/gpx/"+track_id+"/data"
+ passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
+ passman.add_password(None, url, username, password)
+ authhandler = urllib2.HTTPBasicAuthHandler(passman)
+ opener = urllib2.build_opener(authhandler)
+ urllib2.install_opener(opener)
+
+ req = urllib2.urlopen(url)
+ xml = etree.parse(req)
+
+ return xml
+
+def sync_osm(username,password,year,month,dir=".",verbose=False,force=False):
+
+ training_list = get_osm_list(username,password,year,month)
+
+ for training in training_list:
+ filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'])
+ dirname = "%s/%04d/%02d" % (dir,year,month)
+
+ if os.path.exists(filename) and not force:
+
+ if verbose:
+ print "training %s exists, skipping" % (filename)
+
+ else:
+
+ try:
+ os.makedirs(dirname)
+ except:
+ None
+
+ xml = get_osm_gpx(username,password,training['id'])
+
+ if verbose:
+ print "writing training %s" % (filename)
+
+ gpx = pygpx.GPX()
+ gpx.ReadTree(xml)
+
+ gpx.author = username
+ gpx.FixNames(training['sport'])
+ gpx.ProcessTrackSegs()
+ for track in gpx.tracks:
+ track.sport=training['sport']
+
+ xml = gpx.XMLTree();
+ f = open(filename,"w")
+ f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
+ f.close
+ write_parsed_to_db(db,gpx,filename)
+ try:
+ render_tiles.queue_render(db,filename)
+ except:
+ None
+