Debian Codegraph @

extensions/stravaupload/stravaupload.py

raw
1 import json
2 import urllib
3 import urllib2
4 from gi.repository import Gtk
5 import logging
6 import webbrowser
7 from subprocess import Popen, PIPE
8
9 LOGIN_URL = "https://www.strava.com/api/v2/authentication/login"
10 UPLOAD_URL = "http://www.strava.com/api/v2/upload"
11 STATUS_URL = "http://www.strava.com/api/v2/upload/status/%s"
12 ACTIVITY_URL = "http://app.strava.com/activities/"
13
14 class ConfigError(Exception): pass
15
16 class ProgressDialog():
17 def __init__(self, text):
18 self.progress = None
19 self.text = text
20 def __enter__(self):
21 self.progress = Popen(["zenity", "--text", "Strava Upload", "--percentage=0", "--auto-close=True", "--pulsate=True", "--progress", "--no-cancel"], stdin=PIPE)
22 self.progress.stdin.write('# %s\n' % self.text)
23 return self
24
25 def __exit__(self, type, value, traceback):
26 self.progress.stdin.write('100\n')
27 self.progress.stdin.close()
28 self.progress.wait()
29
30 class StravaUpload:
31 def __init__(self, parent = None, pytrainer_main = None, conf_dir = None, options = None):
32 self.pytrainer_main = pytrainer_main
33 self.conf_dir = conf_dir
34
35 self.strava_token = "%s/.strava_token" % self.conf_dir
36 self.strava_uploads = "%s/.strava_uploads" % self.conf_dir
37
38 self.email = None
39 self.password = None
40 if options:
41 self.email = options['stravauploademail']
42 self.password = options['stravauploadpassword']
43
44 def __enter__(self):
45 return self
46
47 def __exit__(self, type, value, traceback):
48 pass
49
50 def get_web_data(self, url, values, text):
51 with ProgressDialog(text) as p:
52 data = urllib.urlencode(values)
53 req = urllib2.Request(url, data)
54 response = urllib2.urlopen(req)
55 return json.loads(response.read())
56
57 def login_token(self):
58 token = None
59 try:
60 with open(self.strava_token) as f:
61 token = f.readline()
62 except:
63 pass
64 if token is None or token.strip() == '' :
65 if self.email and self.password:
66 values = { 'email' : self.email, 'password' : self.password }
67 result = self.get_web_data(LOGIN_URL, values, "Validating user...")
68 token = result['token']
69 else:
70 raise ConfigError("Username or password missing")
71 try:
72 with open(self.strava_token, 'w') as f:
73 f.write(token)
74 except:
75 # didn't write token but that's ok, get another next time...
76 pass
77 return token
78
79 def find_upload(self, id):
80 upload_id = None
81 try:
82 with open(self.strava_uploads) as f:
83 for line in f:
84 upload = line.strip().split(',')
85 if upload[0] == str(id):
86 upload_id = upload[1]
87 break
88 except IOError as e:
89 logging.debug("Failed to read uploads file: %s" % e)
90 return upload_id
91
92 def store_upload_id(self, id, upload_id):
93 try:
94 with open(self.strava_uploads, 'a') as f:
95 f.write('%s,%s\n' % (id, upload_id))
96 except IOError as e:
97 # log failure but continue...
98 logging.debug("Failed to write upload id: %s" % e)
99
100 def get_status(self, token, id):
101 status = None
102 values = { 'token': token }
103 result = self.get_web_data(STATUS_URL % id, values, "Getting status...")
104 if 'activity_id' in result:
105 status = result['activity_id']
106 return status
107
108 def upload(self, token, gpx_file):
109 gpx = None
110 upload_id = 0
111 try:
112 with open(gpx_file) as f:
113 gpx = f.read()
114 except:
115 pass
116 if gpx is not None and gpx.strip() != '':
117 values = { 'token': token, 'type': 'gpx', 'data': gpx }
118 result = self.get_web_data(UPLOAD_URL, values, "Uploading record...")
119 upload_id = result['upload_id']
120 return upload_id
121
122 def run(self, id, activity = None):
123 logging.debug(">>")
124 log = "Strava Upload: "
125 gpx_file = "%s/gpx/%s.gpx" % (self.conf_dir, id)
126 try:
127 logging.debug("Getting user token")
128 user_token = self.login_token();
129 if user_token is not None:
130 existing_id = self.find_upload(id)
131 if existing_id is None:
132 logging.debug("Uploading GPX: %s" % gpx_file)
133 upload_id = self.upload(user_token, gpx_file)
134 if upload_id > 0:
135 self.store_upload_id(id, upload_id)
136 log = log + "success (upload: %s)!" % upload_id
137 else:
138 log = log + "failed to upload!"
139 else:
140 # already uploaded - get status
141 log = "Record already uploaded."
142 status = self.get_status(user_token, existing_id)
143 if status:
144 url = '%s%s' % (ACTIVITY_URL, status)
145 logging.debug(url)
146 log = log + "\n\n%s" % url
147 webbrowser.open(url)
148 else:
149 # don't know status yet, assume it is processing
150 log = log + " Processing... check again soon!"
151 except (ValueError, KeyError) as e:
152 log = log + ("JSON error: %s." % e)
153 except ConfigError as e:
154 log = log + ("config error: %s." % e)
155 except Exception as e:
156 log = "Unknown exception: %s." % e
157 logging.debug(log)
158 md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, log)
159 md.set_title(_("Strava Upload"))
160 md.set_modal(False)
161 md.run()
162 md.destroy()
163 logging.debug("<<")