-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
164 lines (117 loc) · 4.55 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import logging
import os
import time
import requests
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.getLevelName(LOG_LEVEL),
datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
STATUS_HOME = "home"
STATUS_AWAY = "away"
CURRENT_STATUS = None
HOSTS = None
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
def get_nest_access_token():
return os.environ.get("NEST_ACCESS_TOKEN")
def get_google_refresh_token():
return os.environ.get("GOOGLE_REFRESH_TOKEN")
def get_nest_structure():
return os.environ.get("NEST_STRUCTURE")
def get_nest_user():
return os.environ.get("NEST_USER")
def get_nest_rest_endpoint():
return os.environ.get("NEST_REST_ENDPOINT")
def get_hosts_separator():
return os.environ.get("HOSTS_SEPARATOR", ",")
def get_hosts():
return os.environ.get("HOSTS").split(get_hosts_separator())
def get_webhook_ok_url():
return os.environ.get("WEBHOOK_OK_URL")
def get_webhook_fail_url():
return os.environ.get("WEBHOOK_FAIL_URL")
def ping_webhook_url(url: str):
if url:
log.debug(f"calling webhook url: {url}")
requests.get(url, timeout=5)
else:
log.debug("not calling webhook because URL is not set")
def on_success():
log.info(f"set nest status to: {NEW_STATUS} ({r.status_code})")
ping_webhook_url(get_webhook_ok_url())
def on_failure():
log.info(f"failed to set nest status: '{r.text}' ({r.status_code})")
ping_webhook_url(get_webhook_fail_url())
def get_jwt_from_google_refresh_token():
# get access token from google refresh token
r_google_token = requests.post(
'https://oauth2.googleapis.com/token',
data={
'refresh_token': get_google_refresh_token(),
'client_id': '733249279899-1gpkq9duqmdp55a7e5lft1pr2smumdla.apps.googleusercontent.com', # Client ID of the Nest iOS application
'grant_type': 'refresh_token',
},
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': USER_AGENT,
})
if r_google_token.status_code != 200:
raise ValueError(f"failed to get google access token: {r_google_token.text}")
google_access_token = r_google_token.json()['access_token']
# get nest jwt from google access token
r_nest_jwt = requests.post(
'https://nestauthproxyservice-pa.googleapis.com/v1/issue_jwt',
json={
'embed_google_oauth_access_token': True,
'expire_after': '3600s',
'google_oauth_access_token': google_access_token,
'policy_id': 'authproxy-oauth-policy'
},
headers={
'Authorization': 'Bearer ' + google_access_token,
'User-Agent': USER_AGENT,
'Referer': 'https://home.nest.com',
}
)
if r_nest_jwt.status_code != 200:
raise ValueError(f"failed to get nest jwt: {r_nest_jwt.text}")
return r_nest_jwt.json()['jwt']
if __name__ == '__main__':
HOSTS = get_hosts()
log.info(f"found hosts: {HOSTS}")
while True:
NEW_STATUS = None
for host in HOSTS:
try:
requests.get(f"http://{host}", timeout=5)
except requests.exceptions.ConnectionError as e:
if 'Connection refused' in str(e):
log.info(f"{host} is home")
NEW_STATUS = STATUS_HOME
break
else:
NEW_STATUS = STATUS_AWAY
if CURRENT_STATUS != NEW_STATUS:
if get_nest_access_token():
log.debug("using nest account access method")
auth = get_nest_access_token()
else:
log.debug("using google account access method")
auth = get_jwt_from_google_refresh_token()
r = requests.patch(f"{get_nest_rest_endpoint()}/users/{get_nest_user()}/structures/{get_nest_structure()}", json={
'mode': NEW_STATUS
}, headers={
'Content-Type': 'application/json',
'Authorization': f'Basic {auth}'
})
if r.status_code == 200:
CURRENT_STATUS = NEW_STATUS
on_success()
else:
on_failure()
if CURRENT_STATUS == STATUS_HOME:
sleep_delay = 300 # check less often when home
else:
sleep_delay = 15 # check more often when not home
time.sleep(sleep_delay)