-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbeagle_cli.py
341 lines (277 loc) · 10.5 KB
/
beagle_cli.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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import os
import requests
import json
import getpass
from docopt import docopt
from os.path import expanduser
from urllib.parse import urljoin
BEAGLE_ENDPOINT = os.environ.get('BEAGLE_ENDPOINT', 'http://silo:5001')
CONFIG_TEMPLATE = {
'token': '',
'refresh': '',
'next': None,
'prev': None
}
API = {
"auth": "api-token-auth/",
"verify": "api-token-verify/",
"refresh": "api-token-refresh/",
"storage": "v0/fs/storage/",
"file-types": 'v0/fs/file-types/',
"files": '/v0/fs/files/',
}
USAGE = """
Beagle API.
Usage:
beagle_cli.py files create <file_path> <file_type> <file_group_id> [--metadata-path=<metadata_path>] [--size=<size>]
beagle_cli.py files update <file_id> [--file-path=<file_path>] [--file-type=<file_type>] [--file-group=<file_group_id>] [--metadata-path=<metadata_path>] [--size=<size>]
beagle_cli.py files list [--page-size=<page_size>] [--metadata=<metadata>]... [--file-group=<file_group>]... [--file-name=<file_name>]... [--filename-regex=<filename_regex>]
beagle_cli.py storage create <storage_name>
beagle_cli.py storage list
beagle_cli.py file-types create <file_type>
beagle_cli.py file-types list
beagle_cli.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
CONFIG_LOCATION = os.path.join(expanduser("~"), '.beagle.conf')
class Config(object):
def __init__(self, token, refresh, next, prev):
self.token = token
self.refresh = refresh
self.next = next
self.prev = prev
@classmethod
def load(cls):
if os.path.exists(CONFIG_LOCATION):
with open(CONFIG_LOCATION) as config:
config = cls(**json.load(config))
else:
with open(CONFIG_LOCATION, 'w') as config:
config = cls('', '', None, None)
config.dump()
return config
def set(self, key, val):
setattr(self, key, val)
self.dump()
def dump(self):
with open(CONFIG_LOCATION, 'w') as f:
json.dump({'token': self.token, 'refresh': self.refresh, 'next': self.next, 'prev': self.prev}, f)
def __repr__(self):
return 'token: %s, next: %s, prev: %s' % (self.token, self.next, self.prev)
# Commands
def files_commands(arguments, config):
if arguments.get('list'):
return _get_files(arguments, config)
if arguments.get('create'):
return _create_file(arguments, config)
if arguments.get('update'):
return _update_file(arguments, config)
def storage_commands(arguments, config):
if arguments.get('list'):
return _get_storage(arguments, config)
if arguments.get('create'):
return _create_storage(arguments, config)
def file_types_commands(arguments, config):
if arguments.get('list'):
return _get_file_types_command(arguments, config)
if arguments.get('create'):
return _create_file_type(arguments, config)
def command(arguments, config):
if arguments.get('files'):
return files_commands(arguments, config)
if arguments.get('storage'):
return storage_commands(arguments, config)
if arguments.get('file-types'):
return file_types_commands(arguments, config)
# Authentication
def authenticate_command(config):
if _check_is_authenticated(config):
return
while True:
username = input("Username: ")
if not username:
print("Username needs to be specified")
continue
password = getpass.getpass("Password: ")
if not password:
print("Password needs to be specified")
continue
try:
tokens = _authenticate(username, password)
except Exception as e:
print("Invalid username or password")
continue
else:
config.set('token', tokens['access'])
config.set('refresh', tokens['refresh'])
print("Successfully authenticated")
return
def _authenticate(username, password):
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['auth']), {"username": username, "password": password})
if response.status_code == 200:
return response.json()
raise Exception
def _check_is_authenticated(config):
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['verify']), {'token': config.token})
if response.status_code == 200:
return True
else:
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['refresh']), {'refresh': config.refresh})
if response.status_code == 200:
config.set('token', response.json()['access'])
return True
return False
# List commands
def _get_file_types_command(arguments, config):
page_size = arguments.get('--page-size')
params = dict()
if page_size:
params['page_size'] = page_size
response = requests.get(urljoin(BEAGLE_ENDPOINT, API['file-types']),
headers={'Authorization': 'Bearer %s' % config.token}, params=params)
response_json = json.dumps(response.json(), indent=4)
config.set('prev', None)
config.set('next', None)
return response_json
def _get_storage(arguments, config):
page_size = arguments.get('--page-size')
params = dict()
if page_size:
params['page_size'] = page_size
response = requests.get(urljoin(BEAGLE_ENDPOINT, API['storage']), headers={'Authorization': 'Bearer %s' % config.token}, params=params)
response_json = json.dumps(response.json(), indent=4)
_set_next_and_prev(config, response.json())
return response_json
def _get_files(arguments, config):
metadata = arguments.get('--metadata')
file_group = arguments.get('--file-group')
file_name = arguments.get('--file-name')
filename_regex = arguments.get('--filename-regex')
page_size = arguments.get('--page-size')
params = dict()
params['metadata'] = metadata
params['file_group'] = file_group
params['file_name'] = file_name
params['filename_regex'] = filename_regex
if page_size:
params['page_size'] = page_size
response = requests.get(urljoin(BEAGLE_ENDPOINT, API['files']), headers={'Authorization': 'Bearer %s' % config.token}, params=params)
response_json = json.dumps(response.json(), indent=4)
_set_next_and_prev(config, response.json())
return response_json
def _set_next_and_prev(config, value):
config.set('prev', value.get('previous'))
config.set('next', value.get('next'))
def next(config):
response = requests.get(config.next,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
_set_next_and_prev(config, response.json())
return response_json
def prev(config):
response = requests.get(config.prev,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
_set_next_and_prev(config, response.json())
return response_json
# Create
def _create_file(arguments, config):
path = arguments.get('<file_path>')
metadata_path = arguments.get('--metadata-path')
size = arguments.get('--size')
metadata = {}
if metadata_path:
with open(metadata_path) as f:
metadata = json.load(f)
print(metadata)
file_type = arguments.get('<file_type>')
file_group_id = arguments.get('<file_group_id>')
body = {
"path": path,
"metadata": json.dumps(metadata),
"file_group_id": file_group_id,
"file_type": file_type,
}
if size:
body["size"] = size
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['files']), data=body,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
return response_json
def _create_file_type(arguments, config):
ext = arguments.get('<file_type>')
body = {
"ext": ext
}
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['file-types']), data=body,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
return response_json
def _create_storage(arguments, config):
name = arguments.get('<storage_name>')
body = {
"name": name,
"type": 0,
}
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['storage']), data=body,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
return response_json
# Update
def _update_file(arguments, config):
path = arguments.get('<file_path>')
metadata_path = arguments.get('--metadata-path')
size = arguments.get('--size')
metadata = {}
if metadata_path:
with open(metadata_path) as f:
metadata = json.load(f)
print(metadata)
file_type = arguments.get('<file_type>')
file_group_id = arguments.get('<file_group_id>')
body = {
"path": path,
"metadata": json.dumps(metadata),
"file_group_id": file_group_id,
"file_type": file_type,
}
if size:
body["size"] = size
response = requests.post(urljoin(BEAGLE_ENDPOINT, API['files']), data=body,
headers={'Authorization': 'Bearer %s' % config.token})
response_json = json.dumps(response.json(), indent=4)
return response_json
if __name__ == '__main__':
config = Config.load()
authenticate_command(config)
arguments = docopt(USAGE, version='Beagle API 0.1.0')
result = command(arguments, config)
print(result)
if arguments.get('list'):
while config.next or config.prev:
if config.next and config.prev:
page = input("Another page (next, prev): ")
if page == 'next':
result = next(config)
print(result)
elif page == 'prev':
result = prev(config)
print(result)
else:
break
elif config.next and not config.prev:
page = input("Another page (next): ")
if page == 'next':
result = next(config)
print(result)
else:
break
elif not config.next and config.prev:
page = input("Another page (prev): ")
if page:
result = prev(config)
print(result)
else:
break