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'})
30 page = req.text.encode('utf-8')
31 dom = html.document_fromstring(page)
33 for element, attribute, link, pos in dom.iterlinks():
34 if attribute == "href":
35 if link.startswith("/trainings/"):
36 dummy, dummy, link = link.split('/')
37 name, id = link.split('_')
38 trainings.append([ unquote(name), id ])
42 def get_gpx_track(trid,name):
46 req = requests.get("http://www.gps-sport.net/services/trainingGPX.jsp?trainingID=%s&tz=-180" % (trid))
47 xml = etree.fromstring(req.text.encode('utf-8'))
51 def get_osm_list(username,password,year,month):
53 url = "https://www.openstreetmap.org/api/0.6/user/gpx_files"
55 req = requests.get(url,auth=(username,password))
57 xml = etree.fromstring(req.text.encode('utf-8'))
62 attrib = dict(gpx_file.attrib)
64 timestamp=datetime.fromtimestamp(ParseDateTimeUTC(attrib['timestamp']))
67 for descr in gpx_file.iter('description'):
68 description=descr.text
70 for tag in gpx_file.iter('tag'):
72 if timestamp.year==year and timestamp.month==month and description=='Run.GPS Track':
73 record={ 'id': id, 'sport': sport }
80 def get_osm_gpx(username,password,track_id):
82 url = "https://www.openstreetmap.org/api/0.6/gpx/"+track_id+"/data"
84 req = requests.get(url,auth=(username,password))
85 xml = etree.fromstring(req.text.encode('utf-8'))
89 def get_db_gpx(dbx,track_id):
91 md, res = dbx.files_download(track_id)
93 fs = NamedTemporaryFile(suffix='.tcx',delete = False)
97 fs = NamedTemporaryFile(suffix='.gpx',delete = False)
101 os.system("gpsbabel -i gtrnctr -f "+tmp_tcx_name+" -o gpx -F "+tmp_gpx_name)
103 with open (tmp_gpx_name, "r") as gpxfile:
106 os.remove(tmp_gpx_name)
107 os.remove(tmp_tcx_name)
109 xml = etree.fromstring(data.encode('utf-8'))
112 def get_dbx_list(dbx,username,year,month):
116 for entry in dbx.files_list_folder('').entries:
117 if entry.name == u'Приложения':
118 for entry_app in dbx.files_list_folder(entry.id).entries:
119 if entry_app.name == u'Run.GPS':
120 gpx_list_id=entry_app.id
128 for file in dbx.files_list_folder(gpx_list_id).entries:
130 filename,ext = os.path.splitext(file.name)
133 fyear = int(filename[0:4])
134 fmonth = int(filename[5:7])
135 if fyear == year and fmonth == month:
136 sport = filename[18:]
137 timestamp = datetime.strptime(filename[0:16],'%Y-%m-%d_%H%M%S')
138 record={ 'id': file.id, 'timestamp': timestamp, 'sport': sport }
146 def sync_db(dbx,username,year,month,dir=".",verbose=False,force=False):
148 training_list = get_dbx_list(dbx,username,year,month)
150 for training in training_list:
152 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'][3:])
153 dirname = "%s/%04d/%02d" % (dir,year,month)
155 if os.path.exists(filename) and not force:
158 print "training %s exists, skipping" % (filename)
167 xml = get_db_gpx(dbx,training['id'])
170 print "writing training %s" % (filename)
175 sport = training['sport']
176 timestamp = gpx.tracks[0].start_time()
178 print sport, timestamp
180 if check_db_for_training(db,sport,timestamp):
181 print "The same training found"
184 gpx.author = username
185 gpx.FixNames(training['sport'])
186 gpx.ProcessTrackSegs()
187 for track in gpx.tracks:
188 track.sport=training['sport']
191 f = open(filename,"w")
192 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
194 write_parsed_to_db(db,gpx,filename)
196 render_tiles.queue_render(db,filename)
201 def sync_osm(username,password,year,month,dir=".",verbose=False,force=False):
203 training_list = get_osm_list(username,password,year,month)
205 for training in training_list:
207 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'])
208 dirname = "%s/%04d/%02d" % (dir,year,month)
210 if os.path.exists(filename) and not force:
213 print "training %s exists, skipping" % (filename)
222 xml = get_osm_gpx(username,password,training['id'])
225 print "writing training %s" % (filename)
230 sport = training['sport']
231 timestamp = gpx.tracks[0].start_time()
233 if check_db_for_training(db,sport,timestamp):
234 print "The same training found"
237 gpx.author = username
238 gpx.FixNames(training['sport'])
239 gpx.ProcessTrackSegs()
240 for track in gpx.tracks:
241 track.sport=training['sport']
244 f = open(filename,"w")
245 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
247 write_parsed_to_db(db,gpx,filename)
249 render_tiles.queue_render(db,filename)
253 def sync_folder(username,year,month,dir=".",verbose=False,force=False):
255 training_list = get_page(username,year,month)
256 for tr in training_list:
259 filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,(month+1),tr[0],tr[1])
260 dirname = "%s/%04d/%02d" % (dir,year,(month+1))
262 if os.path.exists(filename) and not force:
265 print "training %s exists, skipping" % (filename)
274 xml=get_gpx_track(tr[1],tr[0])
277 print "writing training %s" % (filename)
283 timestamp = gpx.tracks[0].start_time()
285 if check_db_for_training(db,sport,timestamp):
286 print "The same training found"
290 gpx.ProcessTrackSegs()
293 f = open(filename,"w")
294 f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
296 write_parsed_to_db(db,gpx,filename)
298 render_tiles.queue_render(db,filename)
308 parser = OptionParser()
309 parser.add_option("-d", "--dir", dest="dirname",
310 help="write data to directory", metavar="DIR")
311 parser.add_option("-q", "--quiet",
312 action="store_false", dest="verbose", default=True,
313 help="don't print status messages to stdout")
314 parser.add_option("-f", "--force",
315 action="store_true", dest="force", default=False,
316 help="rewrite all files")
317 parser.add_option("-y", "--yearmonth", dest="yearmonth",
318 help="year and month in YYYY-MM format", metavar="YYYY-MM")
319 parser.add_option("-u", "--username", dest="username",
320 help="Run.GPS username")
321 parser.add_option("-o", "--osm-username", dest="osmname",
322 help="OpenStreetMap username")
323 parser.add_option("-p", "--osm-passwd", dest="osmpasswd",
324 help="OpenStreetMap password")
325 parser.add_option("-b", "--dropbox", dest="dropboxauth",
326 help="DropBox Auth token")
327 (options, args) = parser.parse_args()
329 username = options.username
330 osmname = options.osmname
331 osmpwd = options.osmpasswd
332 dbauth = options.dropboxauth
333 if not (username or (osmname and osmpwd) or dbauth):
334 print "Run.GPS username or OSM username/password or Dropbox Auth token is mandatory!"
338 pusername = username+'@Run.GPS'
340 pusername = osmname+'@OSM'
343 dbx = dropbox.Dropbox(dbauth)
344 pusername = dbx.users_get_current_account().email+'@DBX'
347 if options.yearmonth:
348 year,month = options.yearmonth.split('-')
349 month = int(month) -1
351 if month<0 or month>11:
357 print "Year and month should be in YYYY-MM format!"
361 outdir = options.dirname
365 db = outdir + '/gpx.db'
369 print "retrieving trainings for user %s, year %s, month %s to %s" % (pusername,year,month+1,outdir)
371 sync_folder(username,year,month,outdir,options.verbose,options.force)
373 sync_osm(osmname,osmpwd,year,month+1,outdir,options.verbose,options.force)
375 sync_db(dbx,pusername,year,month+1,outdir,options.verbose,options.force)
378 print "retrieving two last months for user %s to %s" % (pusername ,outdir)
380 current_year = now.year
381 current_month = now.month
383 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
385 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
387 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
388 current_month = current_month -1
389 if current_month == 0:
391 current_year = current_year -1
393 sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
395 sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)
397 sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)
399 generate_image.render_all(db,'/etc/mapnik-osm-carto-data/veloroad-transparent.xml',400,400)
401 if __name__ == "__main__":