6 from urllib3.exceptions import InsecureRequestWarning
7 requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
11 from urllib2 import quote,unquote
12 from lxml import html,etree
13 from optparse import OptionParser
14 from datetime import date,datetime
15 from mx.DateTime.ISO import ParseDateTimeUTC
16 from parsegpx import write_parsed_to_db,check_db_for_training
19 from tempfile import NamedTemporaryFile
21 from pprint import pprint
27 def get_page(uname,year,month):
31 req = requests.get("http://www.gps-sport.net/services/getMonthlyTrainingDataHTML_V2.jsp?userName=%s&year=%s&month=%s&rnd=0.645673"% (uname,year,month), headers = {'User-agent': 'Mozilla/5.0'}, verify=False)
32 page = req.text.encode('utf-8')
33 dom = html.document_fromstring(page)
35 for element, attribute, link, pos in dom.iterlinks():
36 if attribute == "href":
37 if link.startswith("/trainings/"):
38 dummy, dummy, link = link.split('/')
39 name, id = link.split('_')
40 trainings.append([ unquote(name), id ])
44 def get_gpx_track(trid,name):
48 req = requests.get("http://www.gps-sport.net/services/trainingGPX.jsp?trainingID=%s&tz=-180" % (trid), verify=False)
49 xml = etree.fromstring(req.text.encode('utf-8'))
53 def get_osm_list(username,password,year,month):
55 url = "https://www.openstreetmap.org/api/0.6/user/gpx_files"
57 req = requests.get(url,auth=(username,password))
59 xml = etree.fromstring(req.text.encode('utf-8'))
64 attrib = dict(gpx_file.attrib)
66 timestamp=datetime.fromtimestamp(ParseDateTimeUTC(attrib['timestamp']))
69 for descr in gpx_file.iter('description'):
70 description=descr.text
72 for tag in gpx_file.iter('tag'):
74 if timestamp.year==year and timestamp.month==month and description=='Run.GPS Track':
75 record={ 'id': id, 'sport': sport }
82 def get_osm_gpx(username,password,track_id):
84 url = "https://www.openstreetmap.org/api/0.6/gpx/"+track_id+"/data"
86 req = requests.get(url,auth=(username,password))
87 xml = etree.fromstring(req.text.encode('utf-8'))
91 def get_db_gpx(dbx,track_id):
93 md, res = dbx.files_download(track_id)
95 fs = NamedTemporaryFile(suffix='.tcx',delete = False)
99 fs = NamedTemporaryFile(suffix='.gpx',delete = False)
103 os.system("gpsbabel -i gtrnctr -f "+tmp_tcx_name+" -o gpx -F "+tmp_gpx_name)
105 with open (tmp_gpx_name, "r") as gpxfile:
108 os.remove(tmp_gpx_name)
109 os.remove(tmp_tcx_name)
111 xml = etree.fromstring(data.encode('utf-8'))
114 def get_dbx_list(dbx,username,year,month):
118 for entry in dbx.files_list_folder('').entries:
119 if entry.name == u'Приложения':
120 for entry_app in dbx.files_list_folder(entry.id).entries:
121 if entry_app.name == u'Run.GPS':
122 print "id="+entry_app.id
123 gpx_list_id=entry_app.id
131 for file in dbx.files_list_folder(gpx_list_id).entries:
133 filename,ext = os.path.splitext(file.name)
136 fyear = int(filename[0:4])
137 fmonth = int(filename[5:7])
138 if fyear == year and fmonth == month:
139 sport = filename[41:]
140 timestamp = datetime.strptime(filename[0:19],'%Y-%m-%dT%H_%M_%S')
141 record={ 'id': file.id, 'timestamp': timestamp, 'sport': sport }
145 fyear = int(filename[0:4])
146 fmonth = int(filename[5:7])
147 if fyear == year and fmonth == month:
148 sport = filename[18:]
149 timestamp = datetime.strptime(filename[0:16],'%Y-%m-%d_%H%M%S')
150 record={ 'id': file.id, 'timestamp': timestamp, 'sport': sport }
158 def sync_db(dbx,username,year,month,dir=".",verbose=False,force=False):
160 training_list = get_dbx_list(dbx,username,year,month)
162 for training in training_list:
164 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'][3:])
165 dirname = "%s/%04d/%02d" % (dir,year,month)
167 if os.path.exists(filename) and not force:
170 print "training %s exists, skipping" % (filename)
179 xml = get_db_gpx(dbx,training['id'])
182 print "writing training %s" % (filename)
187 sport = training['sport']
188 timestamp = gpx.tracks[0].start_time()
190 print sport, timestamp
192 if check_db_for_training(db,sport,timestamp):
193 print "The same training found"
196 gpx.author = username
197 gpx.FixNames(training['sport'])
198 gpx.ProcessTrackSegs()
199 for track in gpx.tracks:
200 track.sport=training['sport']
203 f = open(filename,"w")
204 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
206 write_parsed_to_db(db,gpx,filename)
208 render_tiles.queue_render(db,filename)
213 def sync_osm(username,password,year,month,dir=".",verbose=False,force=False):
215 training_list = get_osm_list(username,password,year,month)
217 for training in training_list:
219 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'])
220 dirname = "%s/%04d/%02d" % (dir,year,month)
222 if os.path.exists(filename) and not force:
225 print "training %s exists, skipping" % (filename)
234 xml = get_osm_gpx(username,password,training['id'])
237 print "writing training %s" % (filename)
242 sport = training['sport']
243 timestamp = gpx.tracks[0].start_time()
245 if check_db_for_training(db,sport,timestamp):
246 print "The same training found"
249 gpx.author = username
250 gpx.FixNames(training['sport'])
251 gpx.ProcessTrackSegs()
252 for track in gpx.tracks:
253 track.sport=training['sport']
256 f = open(filename,"w")
257 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
259 write_parsed_to_db(db,gpx,filename)
261 render_tiles.queue_render(db,filename)
265 def sync_folder(username,year,month,dir=".",verbose=False,force=False):
267 training_list = get_page(username,year,month)
268 for tr in training_list:
271 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,(month+1),tr[0],tr[1])
272 dirname = "%s/%04d/%02d" % (dir,year,(month+1))
274 if os.path.exists(filename) and not force:
277 print "training %s exists, skipping" % (filename)
286 xml=get_gpx_track(tr[1],tr[0])
289 print "writing training %s" % (filename)
295 timestamp = gpx.tracks[0].start_time()
297 if check_db_for_training(db,sport,timestamp):
298 print "The same training found"
302 gpx.ProcessTrackSegs()
305 f = open(filename,"w")
306 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
308 write_parsed_to_db(db,gpx,filename)
310 render_tiles.queue_render(db,filename)
320 parser = OptionParser()
321 parser.add_option("-d", "--dir", dest="dirname",
322 help="write data to directory", metavar="DIR")
323 parser.add_option("-q", "--quiet",
324 action="store_false", dest="verbose", default=True,
325 help="don't print status messages to stdout")
326 parser.add_option("-f", "--force",
327 action="store_true", dest="force", default=False,
328 help="rewrite all files")
329 parser.add_option("-y", "--yearmonth", dest="yearmonth",
330 help="year and month in YYYY-MM format", metavar="YYYY-MM")
331 parser.add_option("-u", "--username", dest="username",
332 help="Run.GPS username")
333 parser.add_option("-o", "--osm-username", dest="osmname",
334 help="OpenStreetMap username")
335 parser.add_option("-p", "--osm-passwd", dest="osmpasswd",
336 help="OpenStreetMap password")
337 parser.add_option("-b", "--dropbox", dest="dropboxauth",
338 help="DropBox Auth token")
339 (options, args) = parser.parse_args()
341 username = options.username
342 osmname = options.osmname
343 osmpwd = options.osmpasswd
344 dbauth = options.dropboxauth
345 if not (username or (osmname and osmpwd) or dbauth):
346 print "Run.GPS username or OSM username/password or Dropbox Auth token is mandatory!"
350 pusername = username+'@Run.GPS'
352 pusername = osmname+'@OSM'
355 dbx = dropbox.Dropbox(dbauth)
356 pusername = dbx.users_get_current_account().email+'@DBX'
359 if options.yearmonth:
360 year,month = options.yearmonth.split('-')
361 month = int(month) -1
363 if month<0 or month>11:
369 print "Year and month should be in YYYY-MM format!"
373 outdir = options.dirname
377 db = outdir + '/gpx.db'
381 print "retrieving trainings for user %s, year %s, month %s to %s" % (pusername,year,month+1,outdir)
383 sync_folder(username,year,month,outdir,options.verbose,options.force)
385 sync_osm(osmname,osmpwd,year,month+1,outdir,options.verbose,options.force)
387 sync_db(dbx,pusername,year,month+1,outdir,options.verbose,options.force)
390 print "retrieving two last months for user %s to %s" % (pusername ,outdir)
392 current_year = now.year
393 current_month = now.month
395 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
397 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
399 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
400 current_month = current_month -1
401 if current_month == 0:
403 current_year = current_year -1
405 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
407 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
409 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
411 generate_image.render_all(db,'/etc/mapnik-osm-carto-data/veloroad-imposm.xml',640,640)
413 if __name__ == "__main__":