Набор скрипотов для работы с веб-сервисом RunGPS - скачивание и обработка треков...
[pyrungps.git] / pyrungps.py
1 #!/usr/bin/env python
2 # coding: UTF-8
3
4 import urllib2
5 #import sys
6 import os
7 from lxml import html,etree
8 from optparse import OptionParser
9 from datetime import date
10 from parsegpx import write_parsed_to_db
11 import pygpx
12
13 def get_page(uname,year,month):
14   
15   trainings = []
16
17   req = urllib2.Request("http://www.gps-sport.net/embedCalendar.jsp?userName=%s&year=%s&month=%s"% (uname,year,month), None, {'User-agent': 'Mozilla/5.0'})
18   page = urllib2.urlopen(req).read()
19   dom = html.document_fromstring(page)
20
21   for element, attribute, link, pos in dom.iterlinks():
22     if attribute == "href":
23       if link.startswith("/trainings/"):
24         dummy, dummy, link = link.split('/')
25         name, id = link.split('_')
26         trainings.append([ urllib2.unquote(name), id ])
27       
28   return trainings      
29
30 def get_gpx_track(trid,name):
31
32   req = urllib2.urlopen("http://www.gps-sport.net/services/trainingGPX.jsp?trainingID=%s" % (trid))
33   
34   xml = etree.parse(req)
35
36   return xml
37
38 def sync_folder(username,year,month,dir=".",verbose=False,force=False):
39
40     training_list = get_page(username,year,month)
41     for tr in training_list:
42
43       filename = "%s/%s_%s.gpx" % (dir,tr[0],tr[1])   
44
45       if os.path.exists(filename) and not force:
46
47         if verbose:
48           print "training %s exists, skipping" % (filename)
49
50       else:  
51     
52         xml=get_gpx_track(tr[1],tr[0])
53
54         if verbose:
55           print "writing training %s" % (filename)
56
57         gpx = pygpx.GPX()
58         gpx.ReadTree(xml)
59
60         gpx.FixNames(tr[0])
61         gpx.ProcessTrackSegs()
62         
63         xml = gpx.XMLTree();
64         f = open(filename,"w")
65         f.write(etree.tostring(xml,encoding='UTF-8',pretty_print=True))
66         f.close
67         write_parsed_to_db(db,gpx,filename)
68
69 def main():
70
71     global db;
72     parser = OptionParser()
73     parser.add_option("-d", "--dir", dest="dirname",
74       help="write data to directory", metavar="DIR")
75     parser.add_option("-q", "--quiet",
76       action="store_false", dest="verbose", default=True,
77       help="don't print status messages to stdout")
78     parser.add_option("-f", "--force",
79       action="store_true", dest="force", default=False,
80       help="rewrite all files")
81     parser.add_option("-y", "--yearmonth", dest="yearmonth",
82       help="year and month in YYYY-MM format", metavar="YYYY-MM")                                                          
83     parser.add_option("-u", "--username", dest="username",
84       help="Run.GPS username")                                                          
85     (options, args) = parser.parse_args()
86
87     username = options.username
88     if not username:
89       print "Run.GPS username is mandatory!"
90       return
91
92     try:
93       if options.yearmonth:
94         year,month = options.yearmonth.split('-')
95         month = int(month) -1
96         year = int(year)
97         if month<0 or month>11:
98           raise invalid_number
99       else:
100         year = None
101         month = None
102     except:
103       print "Year and month should be in YYYY-MM format!"
104       return 
105       
106     if options.dirname:  
107       outdir = options.dirname
108     else:
109       outdir = '.'
110     
111     db = outdir + '/gpx.db'
112     
113     if year:
114       if options.verbose:
115         print "retrieving trainings for user %s, year %s, month %s to %s" % (username,year,month+1,outdir)
116       sync_folder(username,year,month,outdir,options.verbose,options.force)
117     else:
118       if options.verbose:
119         print "retrieving two last months for user %s to %s" % (username,outdir)
120       now = date.today()
121       current_year = now.year
122       current_month = now.month
123       sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
124       current_month = current_month -1
125       if current_month == 0:
126         current_month = 12
127         current_year = current_year -1
128       sync_folder(username,current_year,current_month-1,outdir,options.verbose,options.force)
129
130 if __name__ == "__main__":
131
132     main()                    
133