0f0dc563206b28a58116df86a2b1c2ab3342a2ae
[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         gpx.FixNames(tr[0])
281         gpx.ProcessTrackSegs()
282         
283         xml = gpx.XMLTree();
284         f = open(filename,"w")
285         f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
286         f.close
287         write_parsed_to_db(db,gpx,filename)
288         try:
289           render_tiles.queue_render(db,filename)
290         except:
291           None  
292
293 def main():
294
295     global db;
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()
316
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!"
323       return
324
325     if username:
326       pusername = username+'@Run.GPS'
327     elif osmname:
328       pusername = osmname+'@OSM'  
329     elif dbauth:
330       import dropbox
331       dbx = dropbox.Dropbox(dbauth)  
332       pusername = dbx.users_get_current_account().email+'@DBX'
333
334     try:
335       if options.yearmonth:
336         year,month = options.yearmonth.split('-')
337         month = int(month) -1
338         year = int(year)
339         if month<0 or month>11:
340           raise invalid_number
341       else:
342         year = None
343         month = None
344     except:
345       print "Year and month should be in YYYY-MM format!"
346       return 
347       
348     if options.dirname:  
349       outdir = options.dirname
350     else:
351       outdir = '.'
352     
353     db = outdir + '/gpx.db'
354     
355     if year:
356       if options.verbose:
357         print "retrieving trainings for user %s, year %s, month %s to %s" % (pusername,year,month+1,outdir)
358       if username:
359         sync_folder(username,year,month,outdir,options.verbose,options.force)
360       elif osmname:
361         sync_osm(osmname,osmpwd,year,month+1,outdir,options.verbose,options.force)  
362       elif dbauth:
363         sync_db(dbx,pusername,year,month+1,outdir,options.verbose,options.force)  
364     else:
365       if options.verbose:
366         print "retrieving two last months for user %s to %s" % (pusername ,outdir)
367       now = date.today()
368       current_year = now.year
369       current_month = now.month
370       if username:
371         sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
372       elif osmname:
373         sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)  
374       elif dbauth:
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:
378         current_month = 12
379         current_year = current_year -1
380       if username:
381         sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
382       elif osmname:  
383         sync_osm(osmname,osmpwd,current_year,current_month,outdir,options.verbose,options.force)  
384       elif dbauth:
385         sync_db(dbx,pusername,current_year,current_month,outdir,options.verbose,options.force)  
386
387     generate_image.render_all(db,'/etc/mapnik-osm-carto-data/veloroad-transparent.xml',400,400)
388
389 if __name__ == "__main__":
390
391     main()                    
392