8 from urllib2 import quote,unquote
9 from lxml import html,etree
10 from optparse import OptionParser
11 from datetime import date,datetime
12 from mx.DateTime.ISO import ParseDateTimeUTC
13 from parsegpx import write_parsed_to_db,check_db_for_training
16 from tempfile import NamedTemporaryFile
18 from pprint import pprint
24 def get_page(uname,year,month):
28 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'})
29 page = req.text.encode()
30 dom = html.document_fromstring(page)
32 for element, attribute, link, pos in dom.iterlinks():
33 if attribute == "href":
34 if link.startswith("/trainings/"):
35 dummy, dummy, link = link.split('/')
36 name, id = link.split('_')
37 trainings.append([ unquote(name), id ])
41 def get_gpx_track(trid,name):
45 req = requests.get("http://www.gps-sport.net/services/trainingGPX.jsp?trainingID=%s&tz=-180" % (trid))
46 xml = etree.fromstring(req.text.encode())
50 def get_osm_list(username,password,year,month):
52 url = "https://www.openstreetmap.org/api/0.6/user/gpx_files"
54 req = requests.get(url,auth=(username,password))
56 xml = etree.fromstring(req.text.encode())
61 attrib = dict(gpx_file.attrib)
63 timestamp=datetime.fromtimestamp(ParseDateTimeUTC(attrib['timestamp']))
66 for descr in gpx_file.iter('description'):
67 description=descr.text
69 for tag in gpx_file.iter('tag'):
71 if timestamp.year==year and timestamp.month==month and description=='Run.GPS Track':
72 record={ 'id': id, 'sport': sport }
79 def get_osm_gpx(username,password,track_id):
81 url = "https://www.openstreetmap.org/api/0.6/gpx/"+track_id+"/data"
83 req = requests.get(url,auth=(username,password))
84 xml = etree.fromstring(req.text.encode())
88 def get_db_gpx(dbx,track_id):
90 md, res = dbx.files_download(track_id)
92 fs = NamedTemporaryFile(suffix='.tcx',delete = False)
96 fs = NamedTemporaryFile(suffix='.gpx',delete = False)
100 os.system("gpsbabel -i gtrnctr -f "+tmp_tcx_name+" -o gpx -F "+tmp_gpx_name)
102 with open (tmp_gpx_name, "r") as gpxfile:
105 os.remove(tmp_gpx_name)
106 os.remove(tmp_tcx_name)
108 xml = etree.fromstring(data.encode())
111 def get_dbx_list(dbx,username,year,month):
115 for entry in dbx.files_list_folder('').entries:
116 if entry.name == u'Приложения':
117 for entry_app in dbx.files_list_folder(entry.id).entries:
118 if entry_app.name == u'Run.GPS':
119 gpx_list_id=entry_app.id
127 for file in dbx.files_list_folder(gpx_list_id).entries:
129 filename,ext = os.path.splitext(file.name)
132 fyear = int(filename[0:4])
133 fmonth = int(filename[5:7])
134 if fyear == year and fmonth == month:
135 sport = filename[18:]
136 timestamp = datetime.strptime(filename[0:16],'%Y-%m-%d_%H%M%S')
137 record={ 'id': file.id, 'timestamp': timestamp, 'sport': sport }
145 def sync_db(dbx,username,year,month,dir=".",verbose=False,force=False):
147 training_list = get_dbx_list(dbx,username,year,month)
149 for training in training_list:
151 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'][3:])
152 dirname = "%s/%04d/%02d" % (dir,year,month)
154 if os.path.exists(filename) and not force:
157 print "training %s exists, skipping" % (filename)
166 xml = get_db_gpx(dbx,training['id'])
169 print "writing training %s" % (filename)
174 sport = training['sport']
175 timestamp = gpx.tracks[0].start_time()
177 print sport, timestamp
179 if check_db_for_training(db,sport,timestamp):
180 print "The same training found"
183 gpx.author = username
184 gpx.FixNames(training['sport'])
185 gpx.ProcessTrackSegs()
186 for track in gpx.tracks:
187 track.sport=training['sport']
190 f = open(filename,"w")
191 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
193 write_parsed_to_db(db,gpx,filename)
195 render_tiles.queue_render(db,filename)
200 def sync_osm(username,password,year,month,dir=".",verbose=False,force=False):
202 training_list = get_osm_list(username,password,year,month)
204 for training in training_list:
206 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'])
207 dirname = "%s/%04d/%02d" % (dir,year,month)
209 if os.path.exists(filename) and not force:
212 print "training %s exists, skipping" % (filename)
221 xml = get_osm_gpx(username,password,training['id'])
224 print "writing training %s" % (filename)
229 sport = training['sport']
230 timestamp = gpx.tracks[0].start_time()
232 if check_db_for_training(db,sport,timestamp):
233 print "The same training found"
236 gpx.author = username
237 gpx.FixNames(training['sport'])
238 gpx.ProcessTrackSegs()
239 for track in gpx.tracks:
240 track.sport=training['sport']
243 f = open(filename,"w")
244 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
246 write_parsed_to_db(db,gpx,filename)
248 render_tiles.queue_render(db,filename)
252 def sync_folder(username,year,month,dir=".",verbose=False,force=False):
254 training_list = get_page(username,year,month)
255 for tr in training_list:
257 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,(month+1),tr[0],tr[1])
258 dirname = "%s/%04d/%02d" % (dir,year,(month+1))
260 if os.path.exists(filename) and not force:
263 print "training %s exists, skipping" % (filename)
272 xml=get_gpx_track(tr[1],tr[0])
275 print "writing training %s" % (filename)
281 gpx.ProcessTrackSegs()
284 f = open(filename,"w")
285 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
287 write_parsed_to_db(db,gpx,filename)
289 render_tiles.queue_render(db,filename)
296 parser = OptionParser()
297 parser.add_option("-d", "--dir", dest="dirname",
298 help="write data to directory", metavar="DIR")
299 parser.add_option("-q", "--quiet",
300 action="store_false", dest="verbose", default=True,
301 help="don't print status messages to stdout")
302 parser.add_option("-f", "--force",
303 action="store_true", dest="force", default=False,
304 help="rewrite all files")
305 parser.add_option("-y", "--yearmonth", dest="yearmonth",
306 help="year and month in YYYY-MM format", metavar="YYYY-MM")
307 parser.add_option("-u", "--username", dest="username",
308 help="Run.GPS username")
309 parser.add_option("-o", "--osm-username", dest="osmname",
310 help="OpenStreetMap username")
311 parser.add_option("-p", "--osm-passwd", dest="osmpasswd",
312 help="OpenStreetMap password")
313 parser.add_option("-b", "--dropbox", dest="dropboxauth",
314 help="DropBox Auth token")
315 (options, args) = parser.parse_args()
317 username = options.username
318 osmname = options.osmname
319 osmpwd = options.osmpasswd
320 dbauth = options.dropboxauth
321 if not (username or (osmname and osmpwd) or dbauth):
322 print "Run.GPS username or OSM username/password or Dropbox Auth token is mandatory!"
326 pusername = username+'@Run.GPS'
328 pusername = osmname+'@OSM'
331 dbx = dropbox.Dropbox(dbauth)
332 pusername = dbx.users_get_current_account().email+'@DBX'
335 if options.yearmonth:
336 year,month = options.yearmonth.split('-')
337 month = int(month) -1
339 if month<0 or month>11:
345 print "Year and month should be in YYYY-MM format!"
349 outdir = options.dirname
353 db = outdir + '/gpx.db'
357 print "retrieving trainings for user %s, year %s, month %s to %s" % (pusername,year,month+1,outdir)
359 sync_folder(username,year,month,outdir,options.verbose,options.force)
361 sync_osm(osmname,osmpwd,year,month+1,outdir,options.verbose,options.force)
363 sync_db(dbx,pusername,year,month+1,outdir,options.verbose,options.force)
366 print "retrieving two last months for user %s to %s" % (pusername ,outdir)
368 current_year = now.year
369 current_month = now.month
371 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
373 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
375 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
376 current_month = current_month -1
377 if current_month == 0:
379 current_year = current_year -1
381 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
383 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
385 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
387 generate_image.render_all(db,'/etc/mapnik-osm-carto-data/veloroad-transparent.xml',400,400)
389 if __name__ == "__main__":