forked from jackchi/stshell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstshell
More file actions
executable file
·315 lines (281 loc) · 12.7 KB
/
stshell
File metadata and controls
executable file
·315 lines (281 loc) · 12.7 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python
#
# Copyright 2016 Henric Andersson
#
# The base for a shell like interface to your smartthings account,
# allowing the following:
#
# - Create SA/DTH
# - Upload of individual files to SA/DTH
# - Download of individual files and complete SA/DTH
# - Delete of individual files or complete SA/DTH
#
import argparse
import os
import sys
import re
from classes.console import ConsoleAccess
from classes.stshell import STServer
parser = argparse.ArgumentParser(description="ST Shell - Command Line access to SmartThings WebIDE", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--username', default=None, metavar="EMAIL", help="EMail used for logging into WebIDE")
parser.add_argument('-p', '--password', default=None, help="Password for the account")
parser.add_argument('--server', default="graph.api.smartthings.com", help="Change server to connect to")
subparser = parser.add_subparsers()
parser_list = subparser.add_parser('list', help='Lists all smartapps or devicetype handlers')
parser_list.set_defaults(action="list")
parser_list.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_contents = subparser.add_parser('contents', help='Lists contents of selected bundle')
parser_contents.set_defaults(action="contents")
parser_contents.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_contents.add_argument('UUID', help="The UUID of the bundle to view the contents of")
parser_download = subparser.add_parser('download', help='Download an entire bundle or select parts of it')
parser_download.set_defaults(action="download")
parser_download.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_download.add_argument('UUID', help="The UUID of the bundle to download")
parser_download.add_argument('--item', default=None, help="If defined, the UUID of the item inside the bundle to download", dest='ITEM')
parser_create = subparser.add_parser('create', help="Create a new bundle")
parser_create.set_defaults(action="create")
parser_create.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_create.add_argument('FILE', help="Groovy file for a SmartApp or DeviceType to use for creating the bundle")
parser_upload = subparser.add_parser('upload', help='Upload a file to an existing bundle')
parser_upload.set_defaults(action="upload")
parser_upload.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_upload.add_argument('UUID', help="The UUID of the bundle")
parser_upload.add_argument('TYPE', type=str.upper, choices=STServer.UPLOAD_TYPE.keys(), help="What kind of file (determines base folder)")
parser_upload.add_argument('--path', default="", help="What subpath to place it under", dest='PATH')
parser_upload.add_argument('FILE', help="The file to upload")
parser_delete = subparser.add_parser('delete', help="Delete a bundle or item in a bundle")
parser_delete.set_defaults(action="delete")
parser_delete.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_delete.add_argument('UUID', help="The UUID of the bundle to delete (or delete from)")
parser_delete.add_argument('--item', default=None, help='The item in the bundle to delete', dest='ITEM')
parser_update = subparser.add_parser('update', help='Update an item in the bundle')
parser_update.set_defaults(action="update")
parser_update.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_update.add_argument('UUID', help="The UUID of the bundle to update")
parser_update.add_argument('ITEM', help='The item in the bundle to update')
parser_update.add_argument('FILE', help='The changed file to update the item with')
parser_publish = subparser.add_parser('publish', help="Publish a SmartApp or DeviceType")
parser_publish.set_defaults(action="publish")
parser_publish.add_argument('KIND', type=str.upper, choices=["SA", "DTH"], help="Choose what to operate on (smartapp or devicetype)")
parser_publish.add_argument('UUID', help="The UUID of the bundle to delete (or delete from)")
parser_console = subparser.add_parser('console', help='Enter console mode')
parser_console.set_defaults(action='console')
cmdline = parser.parse_args()
# Try loading the settings
try:
with open(os.path.expanduser('~/.stshell'), "r") as f:
p = re.compile('([^=]+)=(.+)')
for line in f:
m = p.match(line)
if m:
if m.group(1) == "username":
cfg_username = m.group(2).strip()
elif m.group(1) == "password":
cfg_password = m.group(2).strip()
else:
print("Unknown parameter: %s" % (m.group(0)))
except:
pass
if cmdline.username is not None:
cfg_username = cmdline.username
if cmdline.password is not None:
cfg_password = cmdline.password
if cfg_username is None or cfg_password is None:
print("ERROR: Username and password cannot be empty")
sys.exit(255)
if cmdline.action == "console":
sys.stderr.write("Logging in...")
sys.stderr.flush()
srv = STServer(cfg_username, cfg_password, "https://" + cmdline.server)
success = srv.login()
if cmdline.action == "console":
if success:
sys.stderr.write("Done\n")
else:
sys.stderr.write("Failed! Invalid credentials?\n")
sys.exit(255)
sys.stderr.flush()
if not success:
print("Failed to login, invalid credentials?")
sys.exit(255)
if cmdline.action == "list":
# Lists all SA or DTHs
if cmdline.KIND == "DTH": # DTH
types = srv.listDeviceTypes()
else:
types = srv.listSmartApps()
for t in types.values():
print("%36s | %s : %s" % (t["id"], t["namespace"], t["name"]))
elif cmdline.action == "contents":
# Shows the files inside a SA/DTH
if cmdline.KIND == "DTH": # DTH
contents = srv.getDeviceTypeDetails(cmdline.UUID)
else:
contents = srv.getSmartAppDetails(cmdline.UUID)
for k,v in contents["flat"].iteritems():
print("%36s | %s" % (k, v))
elif cmdline.action == "download":
if cmdline.KIND == "DTH": # DTH
if cmdline.ITEM:
contents = srv.getDeviceTypeDetails(cmdline.UUID)
data = srv.downloadDeviceTypeItem(cmdline.UUID, contents["details"], cmdline.ITEM)
with open("./" + data["filename"], "wb") as f:
f.write(data["data"])
else:
srv.downloadDeviceType(cmdline.UUID, "./")
else:
if cmdline.ITEM:
contents = srv.getSmartAppDetails(cmdline.UUID)
data = srv.downloadSmartAppItem(cmdline.UUID, contents["details"], cmdline.ITEM)
with open("./" + data["filename"], "wb") as f:
f.write(data["data"])
else:
srv.downloadSmartApp(cmdline.UUID, "./")
elif cmdline.action == "create":
# Creates a new project, requires a groovy file
with open(cmdline.FILE, "rb") as f:
data = f.read()
if cmdline.KIND == "DTH": # DTH
result = srv.createDeviceType(data)
if result:
print("DeviceType Handler %s created" % result)
else:
print("Failed to create DeviceType Handler")
else:
result = srv.createSmartApp(data)
if result:
print("SmartApp %s created" % result)
else:
print("Failed to create SmartApp")
elif cmdline.action == "delete":
# Deletes an ENTIRE bundle, will prompt before doing so
if cmdline.KIND == "DTH": # DTH
contents = srv.listDeviceTypes()
else:
contents = srv.listSmartApps()
if not cmdline.UUID in contents:
print("ERROR: No such item")
sys.exit(255)
else:
content = contents[cmdline.UUID]
if cmdline.ITEM is None:
sys.stderr.write('Are you SURE you want to delete "%s : %s" (yes/NO) ? ' % (content["namespace"], content["name"]))
sys.stderr.flush()
choice = sys.stdin.readline().strip().lower()
if choice == "yes":
sys.stderr.write("Deleting: ")
sys.stderr.flush()
if cmdline.KIND == "DTH": # DTH
srv.deleteDeviceType(cmdline.UUID)
else:
srv.deleteSmartApp(cmdline.UUID)
sys.stderr.write("Done\n")
else:
sys.stderr.write("Aborted\n")
else:
if cmdline.KIND == "DTH": # DTH
contents = srv.getDeviceTypeDetails(cmdline.UUID)
else:
contents = srv.getSmartAppDetails(cmdline.UUID)
if cmdline.ITEM not in contents["flat"]:
print("ERROR: No such item in bundle")
sys.exit(255)
sys.stderr.write('Are you SURE you want to delete "%s" from "%s : %s" (yes/NO) ? ' % (contents["flat"][cmdline.ITEM], content["namespace"], content["name"]))
sys.stderr.flush()
choice = sys.stdin.readline().strip().lower()
if choice == "yes":
sys.stderr.write("Deleting: ")
sys.stderr.flush()
if cmdline.KIND == "DTH": # DTH
srv.deleteDeviceTypeItem(cmdline.UUID, cmdline.ITEM)
else:
srv.deleteSmartAppItem(cmdline.UUID, cmdline.ITEM)
sys.stderr.write("Done\n")
else:
sys.stderr.write("Aborted\n")
elif cmdline.action == "upload":
# Load content and change filename into the basename
with open(cmdline.FILE, "rb") as f:
data = f.read()
filename = os.path.basename(cmdline.FILE)
if cmdline.TYPE not in STServer.UPLOAD_TYPE:
print("ERROR: Only certain types are supported: " + repr(STServer.UPLOAD_TYPE))
sys.exit(255)
# Download the list of files so we don't try to overwrite (which won't work as you'd expect)
if cmdline.KIND == "DTH": # DTH
details = srv.getDeviceTypeDetails(cmdline.UUID)
else:
details = srv.getSmartAppDetails(cmdline.UUID)
prospect = "/%s/%s/%s" % (STServer.UPLOAD_TYPE[cmdline.TYPE], cmdline.PATH, filename)
p = re.compile('/+')
prospect = p.sub('/', prospect)
if prospect in details["flat"].values():
print('ERROR: "%s" already exists. Cannot replace/update files using upload action' % prospect)
sys.exit(255)
sys.stderr.write("Uploading content: ")
sys.stderr.flush()
if cmdline.KIND == "DTH": # DTH
ids = srv.getDeviceTypeIds(cmdline.UUID)
success = srv.uploadDeviceTypeItem(ids['versionid'], data, filename, cmdline.PATH, cmdline.TYPE)
else:
ids = srv.getSmartAppIds(cmdline.UUID)
success = srv.uploadSmartAppItem(ids['versionid'], data, filename, cmdline.PATH, cmdline.TYPE)
if success:
sys.stderr.write("OK\n")
else:
sys.stderr.write("Failed\n")
elif cmdline.action == "update":
# Bundle UUID, item UUID, new content
with open(cmdline.FILE, 'rb') as f:
data = f.read()
if cmdline.KIND == "DTH": # DTH
details = srv.getDeviceTypeDetails(cmdline.UUID)
else:
details = srv.getSmartAppDetails(cmdline.UUID)
if cmdline.ITEM not in details["flat"]:
print('ERROR: Item is not in selected bundle')
sys.exit(255)
sys.stderr.write("Updating content: ")
sys.stderr.flush()
if cmdline.KIND == "DTH": # DTH
result = srv.updateDeviceTypeItem(details["details"], cmdline.UUID, cmdline.ITEM, data)
else:
result = srv.updateSmartAppItem(details["details"], cmdline.UUID, cmdline.ITEM, data)
if "errors" in result and result["errors"]:
print("Errors:")
for e in result["errors"]:
print(" " + e)
if "output" in result and result["output"]:
print("Details:")
for o in result["output"]:
print(" " + o)
if not result["errors"] and not result["output"]:
print("OK")
else:
sys.exit(1)
elif cmdline.action == "console":
print("Welcome to STShell's console mode, allowing a FTP like access to the backend")
console = ConsoleAccess()
console.setConnection(srv)
console.cmdloop()
print("")
elif cmdline.action == "publish":
# Deletes an ENTIRE bundle, will prompt before doing so
sys.stderr.write("Publishing changes: ")
sys.stderr.flush()
if cmdline.KIND == "DTH": # DTH
contents = srv.listDeviceTypes()
else:
contents = srv.listSmartApps()
if not cmdline.UUID in contents:
print("ERROR: No such item")
sys.exit(255)
if cmdline.KIND == "DTH":
result = srv.publishDeviceType(cmdline.UUID)
else:
result = srv.publishSmartApp(cmdline.UUID)
if result:
print("OK")
else:
print("Failed")