f6ad327a96b48dd250f812290dc684cf7d9ad3b0
[pyrungps.git] / pyrungps.py
1 #!/usr/bin/env python
2 # coding: UTF-8
3
4 import requests
5     
6 #import sys
7 import os
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
14 import pygpx
15
16 from tempfile import NamedTemporaryFile
17
18 from pprint import pprint
19
20 import render_tiles
21
22 import generate_image
23
24 def get_page(uname,year,month):
25   
26   trainings = []
27
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)
31
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 ])
38       
39   return trainings      
40
41 def get_gpx_track(trid,name):
42
43   print "trid=",trid
44
45   req = requests.get("http://www.gps-sport.net/services/trainingGPX.jsp?trainingID=%s&tz=-180" % (trid))
46   xml = etree.fromstring(req.text.encode())
47
48   return xml
49
50 def get_osm_list(username,password,year,month):
51
52   url = "https://www.openstreetmap.org/api/0.6/user/gpx_files"
53
54   req = requests.get(url,auth=(username,password))
55   
56   xml = etree.fromstring(req.text.encode())
57
58   res=[]
59
60   for gpx_file in xml:
61     attrib = dict(gpx_file.attrib)
62     try:
63       timestamp=datetime.fromtimestamp(ParseDateTimeUTC(attrib['timestamp']))
64       id = attrib['id']
65       description=None
66       for descr in gpx_file.iter('description'):
67         description=descr.text
68       sport=None
69       for tag in gpx_file.iter('tag'):
70         sport=tag.text
71       if timestamp.year==year and timestamp.month==month and description=='Run.GPS Track':
72         record={ 'id': id, 'sport': sport }
73         res.append(record)
74     except:
75       None    
76       
77   return res      
78
79 def get_osm_gpx(username,password,track_id):
80
81   url = "https://www.openstreetmap.org/api/0.6/gpx/"+track_id+"/data"
82
83   req = requests.get(url,auth=(username,password))
84   xml = etree.fromstring(req.text.encode())
85
86   return xml
87
88 def get_db_gpx(dbx,track_id):
89
90   md, res = dbx.files_download(track_id)
91
92   fs = NamedTemporaryFile(suffix='.tcx',delete = False)
93   tmp_tcx_name=fs.name
94   fs.write(res.content)
95   fs.close()
96   fs = NamedTemporaryFile(suffix='.gpx',delete = False)
97   tmp_gpx_name=fs.name
98   fs.close()
99   
100   os.system("gpsbabel -i gtrnctr -f "+tmp_tcx_name+" -o gpx -F "+tmp_gpx_name)
101
102   with open (tmp_gpx_name, "r") as gpxfile:
103     data=gpxfile.read()
104     
105   os.remove(tmp_gpx_name)  
106   os.remove(tmp_tcx_name)
107
108   xml = etree.fromstring(data.encode())
109   return xml
110
111 def get_dbx_list(dbx,username,year,month):
112
113     gpx_list_id = None
114
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
120             break
121         break
122
123     res = []
124         
125     if gpx_list_id:
126     
127       for file in dbx.files_list_folder(gpx_list_id).entries:
128         
129         filename,ext = os.path.splitext(file.name)
130         if ext == '.tcx':
131           try:
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 }
138               res.append(record)
139           except:
140             None
141     
142     return res        
143       
144
145 def sync_db(dbx,username,year,month,dir=".",verbose=False,force=False):
146
147     training_list = get_dbx_list(dbx,username,year,month)
148
149     for training in training_list:
150     
151       filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'][3:])   
152       dirname = "%s/%04d/%02d" % (dir,year,month)
153       
154       if os.path.exists(filename) and not force:
155
156         if verbose:
157           print "training %s exists, skipping" % (filename)
158
159       else:  
160
161         try:
162           os.makedirs(dirname)
163         except:
164           None
165
166         xml = get_db_gpx(dbx,training['id'])
167
168         if verbose:
169           print "writing training %s" % (filename)
170
171         gpx = pygpx.GPX()
172         gpx.ReadTree(xml)
173
174         sport = training['sport']
175         timestamp = gpx.tracks[0].start_time()
176         
177         print sport, timestamp
178         
179         if check_db_for_training(db,sport,timestamp):
180           print "The same training found"
181           continue
182
183         gpx.author = username
184         gpx.FixNames(training['sport'])
185         gpx.ProcessTrackSegs()
186         for track in gpx.tracks:
187           track.sport=training['sport']
188
189         xml = gpx.XMLTree();
190         f = open(filename,"w")
191         f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
192         f.close
193         write_parsed_to_db(db,gpx,filename)
194         try:
195           render_tiles.queue_render(db,filename)
196         except:
197           None  
198
199  
200 def sync_osm(username,password,year,month,dir=".",verbose=False,force=False):
201
202     training_list = get_osm_list(username,password,year,month)
203
204     for training in training_list:
205     
206       filename = "%s/%04d/%02d/%s_%s.gpx" % (dir,year,month,training['sport'],training['id'])   
207       dirname = "%s/%04d/%02d" % (dir,year,month)
208
209       if os.path.exists(filename) and not force:
210
211         if verbose:
212           print "training %s exists, skipping" % (filename)
213
214       else:  
215       
216         try:
217           os.makedirs(dirname)    
218         except:
219           None
220
221         xml = get_osm_gpx(username,password,training['id'])
222
223         if verbose:
224           print "writing training %s" % (filename)
225
226         gpx = pygpx.GPX()
227         gpx.ReadTree(xml)
228
229         sport = training['sport']
230         timestamp = gpx.tracks[0].start_time()
231         
232         if check_db_for_training(db,sport,timestamp):
233           print "The same training found"
234           continue
235
236         gpx.author = username
237         gpx.FixNames(training['sport'])
238         gpx.ProcessTrackSegs()
239         for track in gpx.tracks:
240           track.sport=training['sport']
241
242         xml = gpx.XMLTree();
243         f = open(filename,"w")
244         f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
245         f.close
246         write_parsed_to_db(db,gpx,filename)
247         try:
248           render_tiles.queue_render(db,filename)
249         except:
250           None  
251
252 def sync_folder(username,year,month,dir=".",verbose=False,force=False):
253
254     training_list = get_page(username,year,month)
255     for tr in training_list:
256
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))
259
260       if os.path.exists(filename) and not force:
261
262         if verbose:
263           print "training %s exists, skipping" % (filename)
264
265       else:  
266
267         try:
268           os.makedirs(dirname)    
269         except:
270           None
271           
272         xml=get_gpx_track(tr[1],tr[0])
273
274         if verbose:
275           print "writing training %s" % (filename)
276
277         gpx = pygpx.GPX()
278         gpx.ReadTree(xml)
279
280         sport = training['sport']
281         timestamp = gpx.tracks[0].start_time()
282         
283         if check_db_for_training(db,sport,timestamp):
284           print "The same training found"
285           continue
286
287         gpx.FixNames(tr[0])
288         gpx.ProcessTrackSegs()
289         
290         xml = gpx.XMLTree();
291         f = open(filename,"w")
292         f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
293         f.close
294         write_parsed_to_db(db,gpx,filename)
295         try:
296           render_tiles.queue_render(db,filename)
297         except:
298           None  
299
300 def main():
301
302     global db;
303     parser = OptionParser()
304     parser.add_option("-d", "--dir", dest="dirname",
305       help="write data to directory", metavar="DIR")
306     parser.add_option("-q", "--quiet",
307       action="store_false", dest="verbose", default=True,
308       help="don't print status messages to stdout")
309     parser.add_option("-f", "--force",
310       action="store_true", dest="force", default=False,
311       help="rewrite all files")
312     parser.add_option("-y", "--yearmonth", dest="yearmonth",
313       help="year and month in YYYY-MM format", metavar="YYYY-MM")                                                          
314     parser.add_option("-u", "--username", dest="username",
315       help="Run.GPS username")                                                          
316     parser.add_option("-o", "--osm-username", dest="osmname",
317       help="OpenStreetMap username")                                                          
318     parser.add_option("-p", "--osm-passwd", dest="osmpasswd",
319       help="OpenStreetMap password")                                                          
320     parser.add_option("-b", "--dropbox", dest="dropboxauth",
321       help="DropBox Auth token")                                                          
322     (options, args) = parser.parse_args()
323
324     username = options.username
325     osmname = options.osmname
326     osmpwd = options.osmpasswd
327     dbauth = options.dropboxauth
328     if not (username or (osmname and osmpwd) or dbauth):
329       print "Run.GPS username or OSM username/password or Dropbox Auth token is mandatory!"
330       return
331
332     if username:
333       pusername = username+'@Run.GPS'
334     elif osmname:
335       pusername = osmname+'@OSM'  
336     elif dbauth:
337       import dropbox
338       dbx = dropbox.Dropbox(dbauth)  
339       pusername = dbx.users_get_current_account().email+'@DBX'
340
341     try:
342       if options.yearmonth:
343         year,month = options.yearmonth.split('-')
344         month = int(month) -1
345         year = int(year)
346         if month<0 or month>11:
347           raise invalid_number
348       else:
349         year = None
350         month = None
351     except:
352       print "Year and month should be in YYYY-MM format!"
353       return 
354       
355     if options.dirname:  
356       outdir = options.dirname
357     else:
358       outdir = '.'
359     
360     db = outdir + '/gpx.db'
361     
362     if year:
363       if options.verbose:
364         print "retrieving trainings for user %s, year %s, month %s to %s" % (pusername,year,month+1,outdir)
365       if username:
366         sync_folder(username,year,month,outdir,options.verbose,options.force)
367       elif osmname:
368         sync_osm(osmname,osmpwd,year,month+1,outdir,options.verbose,options.force)  
369       elif dbauth:
370         sync_db(dbx,pusername,year,month+1,outdir,options.verbose,options.force)  
371     else:
372       if options.verbose:
373         print "retrieving two last months for user %s to %s" % (pusername ,outdir)
374       now = date.today()
375       current_year = now.year
376       current_month = now.month
377       if username:
378         sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
379       elif osmname:
380         sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)  
381       elif dbauth:
382         sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)  
383       current_month = current_month -1
384       if current_month == 0:
385         current_month = 12
386         current_year = current_year -1
387       if username:
388         sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
389       elif osmname:  
390         sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)  
391       elif dbauth:
392         sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)  
393
394     generate_image.render_all(db,'/etc/mapnik-osm-carto-data/veloroad-transparent.xml',400,400)
395
396 if __name__ == "__main__":
397
398     main()                    
399