forked from Screenly/Anthias
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassets-migration-to-screenly-pro.py
216 lines (172 loc) · 6.19 KB
/
assets-migration-to-screenly-pro.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
# -*- coding: utf-8 -*-
import os
import sys
import traceback
import sh
import click
import requests
import time
from requests.auth import HTTPBasicAuth
HOME = os.getenv('HOME', '/home/pi')
BASE_API_SCREENLY_URL = 'https://api.screenlyapp.com'
ASSETS_SCREENLY_OSE_API = 'http://127.0.0.1/api/v1.1/assets'
PORT_NGROK = 4040
PORT = 80
token = None
ngrok_public_url = None
################################
# Suprocesses
################################
def start_http_ngrok_process(try_connection=100):
click.echo(click.style("Ngrok starting ...", fg='yellow'))
sh.ngrok('http', str(PORT), _bg=True, _in=os.devnull, _out=os.devnull, _err=sys.stderr)
try_count = 0
while True:
if try_count >= try_connection:
raise Exception('Failed start ngrok')
try:
requests.get('http://127.0.0.1:%i' % PORT_NGROK, timeout=10)
break
except requests.exceptions.ConnectionError:
try_count += 1
time.sleep(0.1)
click.echo(click.style("Ngrok successfull started", fg='green'))
def get_ngrock_public_url(try_connection=100):
try_count = 0
while True:
if try_count >= try_connection:
raise Exception('Could not take a public url ngrok')
response = requests.get('http://127.0.0.1:%i/api/tunnels' % PORT_NGROK, timeout=10).json()
if response['tunnels']:
break
else:
try_count += 1
time.sleep(0.1)
continue
return response['tunnels'][0]['public_url']
################################
# Utilities
################################
def progress_bar(count, total, text=''):
"""
This simple console progress bar
For display progress asset uploads
"""
progress_line = "\xe2" * int(round(50 * count / float(total))) + '-' * (50 - int(round(50 * count / float(total))))
percent = round(100.0 * count / float(total), 1)
sys.stdout.write('[%s] %s%s %s\r' % (progress_line, percent, '%', text))
sys.stdout.flush()
def set_token(value):
global token
token = 'Token %s' % value
def set_ngrok_public_url(value):
global ngrok_public_url
ngrok_public_url = value
################################
# Database
################################
def get_assets_by_screenly_ose_api():
if click.confirm('Do you need authentication to access Screenly-OSE API?'):
login = click.prompt('Login')
password = click.prompt('Password', hide_input=True)
auth = HTTPBasicAuth(login, password)
else:
auth = None
response = requests.get(ASSETS_SCREENLY_OSE_API, timeout=10, auth=auth)
if response.status_code == 200:
return response.json()
elif response.status_code == 401:
raise Exception('Access denied')
################################
# Requests
################################
def send_asset(asset):
endpoind_url = '%s/api/v3/assets/' % BASE_API_SCREENLY_URL
headers = {
'Authorization': token
}
asset_uri = asset['uri']
if asset_uri.startswith(HOME):
asset_uri = os.path.join(ngrok_public_url, asset['asset_id'])
data = {
'title': asset['name'],
'source_url': asset_uri
}
response = requests.post(endpoind_url, data=data, headers=headers)
return response.status_code == 200
def check_validate_token(api_key):
endpoind_url = '%s/api/v3/assets/' % BASE_API_SCREENLY_URL
headers = {
'Authorization': 'Token %s' % api_key
}
response = requests.get(endpoind_url, headers=headers)
if response.status_code == 200:
return api_key
else:
return None
def get_api_key_by_credentials(username, password):
endpoind_url = '%s/api/v3/tokens/' % BASE_API_SCREENLY_URL
data = {
'username': username,
'password': password
}
response = requests.post(endpoind_url, data=data)
if response.status_code == 200:
return response.json()['token']
else:
return None
################################
################################
def start_migration():
if click.confirm('Do you want to start assets migration?'):
click.echo('\n')
start_http_ngrok_process()
set_ngrok_public_url(get_ngrock_public_url())
click.echo('\n')
assets_migration()
def assets_migration():
assets = get_assets_by_screenly_ose_api()
assets_length = len(assets)
click.echo('\n')
for index, asset in enumerate(assets):
asset_name = str(asset['name'])
progress_bar(index + 1, assets_length, text='Asset in migration progress: %s' % asset_name)
status = send_asset(asset)
if not status:
click.echo(click.style('\n%s asset was failed migration' % asset_name, fg='red'))
click.echo('\n')
click.echo(click.style('Migration completed successfully', fg='green'))
@click.command()
@click.option('--method',
prompt='What do you want to use for migration?\n1.API token\n2.Credentials\n0.Exit\nYour choice',
type=click.Choice(['1', '2', '0']))
def main(method):
try:
valid_token = None
if method == '1':
api_key = click.prompt('Your API key')
valid_token = check_validate_token(api_key)
elif method == '2':
username = click.prompt('Your username')
password = click.prompt('Your password', hide_input=True)
valid_token = get_api_key_by_credentials(username, password)
elif method == '0':
sys.exit(0)
if valid_token:
set_token(valid_token)
click.echo(click.style('Successfull authentication', fg='green'))
start_migration()
else:
click.echo(click.style('Failed authentication', fg='red'))
except Exception:
traceback.print_exc()
if __name__ == '__main__':
click.echo(click.style("""
_____ __ ____ _____ ______
/ ___/_____________ ___ ____ / /_ __ / __ \/ ___// ____/
\__ \/ ___/ ___/ _ \/ _ \/ __ \/ / / / / / / / /\__ \/ __/
___/ / /__/ / / __/ __/ / / / / /_/ / / /_/ /___/ / /___
/____/\___/_/ \___/\___/_/ /_/_/\__, / \____//____/_____/
/____/
""", fg='blue'))
main()