-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdeploy.py
executable file
·222 lines (175 loc) · 6.17 KB
/
deploy.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python
# pip3 install python-dotenv requests simplejson
try:
# base
import argparse
import os
import re
# import subprocess
import json
import pathlib
# dotenv
from dotenv import load_dotenv, find_dotenv
# import urllib.parse
import time
import requests
import http.cookiejar
import sys
except ModuleNotFoundError as e:
print("ModuleNotFoundError exception while attempting to import the needed modules: " + str(e))
exit(99)
def find_files(find='.'):
data = []
for root, directories, filenames in os.walk(find):
for filename in filenames:
data.append({'name': filename.replace('.groovy', ''), 'path': os.path.join(root, filename)})
return data
def merge_data(local, remote):
data = []
for l in local:
# print(l)
for h in remote:
if h['name'] == l['name']:
data.append(dict(l, **h))
return data
def update_driver(s, drv):
print("> Processing Driver: " + drv['name'] + " (" + str(drv['id']) + ")")
response = s.get(
url=he_url + "/driver/ajax/code",
params={'id': drv['id']}
)
# print(response.text)
if (response.json()['status'] != "success"):
print("\tFailed downloading")
return None
version = response.json()['version']
print("\tCurrent version: " + str(version))
print("\tUploading driver")
with open(drv['path'], 'r') as f:
sourceContents = f.read()
response = s.post(
url=he_url + "/driver/ajax/update",
data={'id': drv['id'],
'version': version,
'source': sourceContents
}
)
# print(response.text)
if(response.json()['status'] == "success"):
print("\tSuccessfully uploaded")
elif (response.json()['status'] == "error"):
print("\tFailed uploading: " + response.json()['errorMessage'])
return None
else:
print("\tFailed uploading: " + response.json())
return None
def update_app(s, app):
print("> Processing App: " + app['name'] + " (" + str(app['id']) + ")")
response = s.get(
url=he_url + "/app/ajax/code",
params={'id': app['id']}
)
# print(response.text)
if (response.json()['status'] != "success"):
print("\tFailed downloading")
return None
version = response.json()['version']
print("\tCurrent version: " + str(version))
print("\tUploading app")
with open(app['path'], 'r') as f:
sourceContents = f.read()
response = s.post(
url=he_url + "/app/ajax/update",
data={'id': app['id'],
'version': version,
'source': sourceContents
}
)
# print(response.text)
if(response.json()['status'] == "success"):
print("\tSuccessfully uploaded")
elif (response.json()['status'] == "error"):
print("\tFailed uploading: " + response.json()['errorMessage'])
return None
else:
print("\tFailed uploading: " + response.json())
return None
def he_login(path):
credentialStorageFolderPath = pathlib.Path(path, ".creds")
cookieJarFilePath = pathlib.Path(credentialStorageFolderPath, "cookie-jar.txt")
# print("str(cookieJarFilePath.resolve()): " + str(cookieJarFilePath.resolve()))
session = requests.Session()
cookieJarFilePath.resolve().parent.mkdir(parents=True, exist_ok=True)
session.cookies = http.cookiejar.MozillaCookieJar(filename=str(cookieJarFilePath.resolve()))
# Ensure that the cookie jar file exists and contains a working cookie to authenticate into the hubita web interface
if os.path.isfile(session.cookies.filename):
session.cookies.load(ignore_discard=True)
else:
# Collect username and password from the user
print("Hubitat username: ")
hubitatUsername = input()
print("Hubitat password: ")
hubitatPassword = input()
print("Entered " + hubitatUsername + " and " + hubitatPassword)
response = session.post(
he_url + "/login",
data={
'username': hubitatUsername,
'password': hubitatPassword,
'submit': 'Login'
}
)
# print("cookies: " + str(response.cookies.get_dict()))
session.cookies.save(ignore_discard=True)
return session
# ------------------------------------ MAIN
load_dotenv(find_dotenv(), verbose=True)
fs_base = pathlib.Path(os.getcwd()).resolve()
he_url = os.getenv("HE_URL")
if he_url == None:
print("HE_URL is not defined in the .env file")
exit(99)
print("Connecting to: " + he_url)
session = he_login(fs_base)
# ------------------------------------ DRIVERS
# Find Local Drivers
local_drivers = find_files(pathlib.Path(fs_base, "Drivers").resolve())
# print(local_drivers)
# Load Remote Drivers
resp = session.get(url=he_url + "/driver/list/data")
# Check loging session
if 'X-Frame-Options' in resp.headers and resp.headers['X-Frame-Options'] == 'DENY':
print("Your HE Login Session has expired or been reseted, delete the file: .creds/cookie-jar.txt")
exit(1)
he_drivers = resp.json()
# print(he_drivers)
# Filter out system drivers
he_drivers_usr = [x for x in he_drivers if x['type'] == 'usr']
# print(he_drivers_usr)
drvs = merge_data(he_drivers_usr, local_drivers)
print("Found HE Drivers: " + str(len(drvs)))
# print("Found HE Drivers: " + str(drv))
for d in drvs:
update_driver(session, d)
# ------------------------------------ APP
# Find Local Apps
local_apps = find_files(pathlib.Path(fs_base, "Apps").resolve())
# print(local_apps)
# Load Remote Apps
resp = session.get(url=he_url + "/app/list/data")
# Check loging session
if 'X-Frame-Options' in resp.headers and resp.headers['X-Frame-Options'] == 'DENY':
print("Your HE Login Session has expired or been reseted, delete the file: .creds/cookie-jar.txt")
exit(1)
# print(resp)
he_apps = resp.json()
# print(he_apps)
# Filter out system apps
he_apps_usr = [x for x in he_apps if x['type'] == 'usr']
# print(he_apps_usr)
apps = merge_data(he_apps_usr, local_apps)
print("Found HE Apps: " + str(len(apps)))
# print("Found HE Apps: " + str(apps))
for a in apps:
update_app(session, a)
exit(0)