/
app_tcp_handler.py
81 lines (72 loc) · 2.87 KB
/
app_tcp_handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import SocketServer
import base64
import requests
import json
from jinja2 import Template
from app_constants import AppConstants
from fitbit import FitBit
class AppTCPHandler(SocketServer.StreamRequestHandler):
last_code = None
def outputPage(self, page):
print page
self.wfile.write(page)
def handleFitbit(self):
print "----HANDLING FITBIT OAUTH REQUEST----"
code = self.data[self.data.find("code")+5:self.data.find("HTTP")-1]
if code == AppTCPHandler.last_code:
print "----IGNORING DUPLICATE----"
retval=self.generateClosePage()
self.outputPage(retval)
return
print "{} and {} are not equal".format(code,AppTCPHandler.last_code)
AppTCPHandler.last_code = code
payload={"grant_type":"authorization_code",
"client_id":FitBit.creds['client_id'],
"redirect_uri":"http://localhost/fitbit",
"code":code}
authraw="{}:{}".format(FitBit.creds['client_id'], FitBit.creds['client_secret'])
b64auth="Basic "+base64.b64encode(authraw)
print "Code:",code
print "Payload:",payload
print "Fitbit:",authraw
print "Base64Auth:",b64auth
print "----SENDING TOKEN REQUEST----"
response=requests.post("https://api.fitbit.com/oauth2/token",
data=payload,
headers={"Authorization":b64auth,"Content-Type":"application/x-www-form-urlencoded"})
print response.headers
print response.text
parsed = json.loads(response.text)
FitBit.storeLogin(parsed)
FitBit.pullFromServer()
retval=self.generateClosePage()
self.outputPage(retval)
def handle(self):
trysite=None
self.data = self.request.recv(2048)
print self.data
if "GET /fitbit?code=" in self.data:
self.handleFitbit()
return
print "----GENERATING WEBSITE---"
for t in AppConstants.THRESHOLDS:
if t[0] in self.data:
trysite = t
break
retval=self.generateSite(trysite)
self.outputPage(retval)
print "----REQUEST COMPLETE----"
def generateSite(self, site):
"""Generate site based on steps and URL being visited"""
template = Template(
open('template.html', 'r').read()
)
print FitBit.steps
print "Generating with steps={} site={} goal={}".format(FitBit.steps.getVal(), site, FitBit.goal.getVal())
return template.render(steps=FitBit.steps.getVal(), site=site, goal=FitBit.goal.getVal())
def generateClosePage(self):
"""Generates a site that just closes itself (for auth purposes)"""
template = Template(
open('close.html', 'r').read()
)
return template.render()