-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcameras_migrate_to_cloud_two.py
453 lines (397 loc) · 12.5 KB
/
cameras_migrate_to_cloud_two.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import argparse
import os
import logging
import requests
def get_co_headers(lkey: str) -> Dict[str, str]:
return {
"accept": "application/json",
"Authorization": f"LKey {lkey}",
"Content-Type": "application/json",
}
def get_ct_headers(token) -> Dict[str, str]:
return {
"accept": "application/json",
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def get_cloud_two_auth(email: str, password: str, endpoint: str) -> dict:
api_endpoint = f"https://{endpoint}/v1/auth"
data = {
"email": email,
"password": password
}
auth_request = requests.post(
url=api_endpoint,
json=data,
timeout=10
)
if auth_request.status_code != 200:
logging.error("Failed to fetch auth token for %s/%s", email, password)
return {}
resp = auth_request.json()
logging.info("Received access token: %s", resp["accessToken"])
logging.info("Received company ID: %s", resp["session"]["company"]["id"])
return {
"access_token": resp["accessToken"],
"company_id": resp["session"]["company"]["id"]
}
def add_lkey_to_cloud_two(
auth_token: str,
company_id: str,
endpoint: str,
co_endpoint: str,
lkey: str
):
headers = get_ct_headers(token=auth_token)
api_endpoint = f"https://{endpoint}/v1/company/{company_id}/auth"
data = {
"lKey": lkey,
"endpoint": f"https://{co_endpoint}/"
}
company_request = requests.patch(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if company_request.status_code != 200:
logging.error("Failed to add LKey to company.")
def create_cloud_two_site(auth_token: str, endpoint: str) -> int:
'''
:param auth_token: str of cloudtwo auth token
:return id: int of site id created
'''
headers = get_ct_headers(token=auth_token)
data = {
"site": [
{"name": "cloudone"}
],
"location": {
"city": "Toronto",
"state": "Ontario",
"country": "Canada",
"address": "3080 Yonge St, Toronto, ON M4N 2K4, Canada",
"latitude": 43.72528319999999,
"longitude": -79.4025985
}
}
api_endpoint = f"https://{endpoint}/v1/site"
site_request = requests.post(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if site_request.status_code != 200:
logging.error("Failed to create site.")
return 0
resp = site_request.json()
logging.info("Created site %d", resp["location"]["id"])
return resp["location"]["id"]
def get_channel_group_id_for_site(site_id: int, endpoint: str, lkey: str) -> int:
'''
Get channel_group id with name = Site<ID>
'''
site = f"Site{site_id}"
headers = get_co_headers(lkey=lkey)
api_endpoint = f"https://{endpoint}/api/v3/channel_groups/?limit=1000"
# Fetch group channels
cg_request = requests.get(
url=api_endpoint,
headers=headers,
timeout=10
)
if cg_request.status_code != 200:
logging.error("Failed to get channel groups.")
return 0
for channel_group in cg_request.json()["objects"]:
if channel_group["name"] == site:
logging.info(
"Successfully got channel group ID: %d.",
channel_group["id"]
)
return channel_group["id"]
logging.error("Site not found in Channel Groups.")
return 0
def get_cloud_one_channels(lkey: str, endpoint: str) -> list[int]:
channels = []
headers = get_co_headers(lkey=lkey)
api_endpoint = f"https://{endpoint}/api/v3/channels/?limit=1000"
# Fetch group channels
channel_request = requests.get(
url=api_endpoint,
headers=headers,
timeout=10
)
if channel_request.status_code != 200:
logging.error("Failed to get channels: %s", channel_request.text)
return []
resp = channel_request.json()
# Build list of channels
for channel in resp["objects"]:
channels.append(channel["id"])
# Get additional channels if account has >1000 channels
while resp["meta"]["next"]:
api_endpoint = f"https://{endpoint}{resp['meta']['next']}"
channel_request = requests.get(
url=api_endpoint,
headers=headers,
timeout=10
)
if channel_request.status_code != 200:
logging.error("Failed to get channels: %s", channel_request.text)
return []
resp = channel_request.json()
# Build list of channels
for channel in resp["objects"]:
channels.append(channel["id"])
logging.info("Successfully got all channels: %s", str(channels))
return channels
def add_channels_to_site(cg_id: int, channels: list[int], lkey: str, endpoint: str) -> str:
'''
return: token from channel_group
'''
headers = get_co_headers(lkey=lkey)
api_endpoint = f"https://{endpoint}/api/v3/channel_groups/{cg_id}/"
data = {
"channels": channels
}
cg_request = requests.put(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if cg_request.status_code != 200:
logging.error("Failed to update channel group: %s", cg_request.text)
return ""
resp = cg_request.json()
logging.info("Successfully added channels to channel group.")
return resp["token"]
def update_site_group_token(auth_token: str, group_token: str, site_id: int, endpoint: str):
headers = get_ct_headers(token=auth_token)
api_endpoint = f"https://{endpoint}/v1/site/{site_id}"
data = {
"groupToken": group_token
}
site_request = requests.patch(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if site_request.status_code != 200:
logging.error("Failed to update group token for size.")
return
logging.info("Successfully updated site group token.")
def update_channel_meta(ch_id: int, lkey: str, endpoint: str, site_id: int):
# { "data": "NOPLAN", "tag": "planId"}
# { "data": "siteId", "tag": str(site_id)}
# { "data": str(siteId), "tag": "siteId"}
headers = get_co_headers(lkey=lkey)
api_endpoint = f"https://{endpoint}/api/v3/channels/{ch_id}/meta/"
data = {
"data": "NOPLAN",
"tag": "planId"
}
cg_request = requests.post(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if cg_request.status_code != 201:
# 400 indicates tag already exists, update it
if cg_request.status_code == 400:
meta_api_endpoint = f"{api_endpoint}planId/"
meta_data = {
"data": "NOPLAN"
}
update_req = requests.put(
url=meta_api_endpoint,
headers=headers,
json=meta_data,
timeout=10
)
if update_req.status_code != 200:
logging.error("Failed to update channel group meta: %s", update_req.text)
return
else:
logging.error("Failed to update channel group meta: %s", cg_request.text)
return
data = {
"data": "siteId",
"tag": str(site_id)
}
cg_request = requests.post(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if cg_request.status_code != 201:
# 400 indicates tag already exists, update it
if cg_request.status_code == 400:
meta_api_endpoint = f"{api_endpoint}{str(site_id)}/"
meta_data = {
"data": "siteId"
}
update_req = requests.put(
url=meta_api_endpoint,
headers=headers,
json=meta_data,
timeout=10
)
if update_req.status_code != 200:
logging.error("Failed to update channel group meta: %s", update_req.text)
return
else:
logging.error("Failed to update channel group meta: %s", cg_request.text)
return
data = {
"data": str(site_id),
"tag": "siteId"
}
cg_request = requests.post(
url=api_endpoint,
headers=headers,
json=data,
timeout=10
)
if cg_request.status_code != 201:
# 400 indicates tag already exists, update it
if cg_request.status_code == 400:
meta_api_endpoint = f"{api_endpoint}siteId/"
meta_data = {
"data": str(site_id)
}
update_req = requests.put(
url=meta_api_endpoint,
headers=headers,
json=meta_data,
timeout=10
)
if update_req.status_code != 200:
logging.error("Failed to update channel group meta: %s", update_req.text)
return
else:
logging.error("Failed to update channel group meta: %s", cg_request.text)
return
logging.info("Successfully updated channel %s meta.", str(ch_id))
def main():
'''
Required params
co_endpoint: cloudone api endpoint
ct_endpoint: cloudtwo api endpoint
email: cloudtwo email
password: cloudtwo password
lkey: cloudone LKey token
Optional params
cameras: string of cam_ids to manually add
'''
logging.basicConfig(
format="%(asctime)s %(filename)s %(levelname)s: %(message)s",
level=os.environ.get("LOGGING", "INFO"),
)
parser = argparse.ArgumentParser(description="")
# Add arguments
parser.add_argument(
"--co_endpoint",
help="URL to Cloudone API for example https://vms.com",
required=True
)
parser.add_argument(
"--ct_endpoint",
help="URL to Cloudone API for example https://vms.com",
required=True
)
parser.add_argument(
"--lkey",
help="License key for the API V3",
required=True
)
parser.add_argument(
"--password",
help="Password for cloudtwo account",
required=True
)
parser.add_argument(
"--email",
help="Email for cloudtwo account",
required=True
)
parser.add_argument(
"--cameras",
help="List of cameras IDs to move. Example: 123,124,125",
default=""
)
args = parser.parse_args()
if args.cameras != "":
# Parse list
try:
channels = []
cameras = args.cameras.split(",")
for cam in cameras:
channels.append(int(cam))
except Exception as e:
logging.error("Error parsing provided camera IDs.")
raise Exception(e)
else:
# No list provided so we must fetch channels
channels = get_cloud_one_channels(lkey=args.lkey, endpoint=args.co_endpoint)
if not channels:
raise Exception("No channels found.")
auth_dict = get_cloud_two_auth(
email=args.email,
password=args.password,
endpoint=args.ct_endpoint
)
if auth_dict:
auth_token = auth_dict["access_token"]
company_id = auth_dict["company_id"]
else:
raise Exception("No auth_token or company_id found.")
add_lkey_to_cloud_two(
auth_token=auth_token,
company_id=company_id,
endpoint=args.ct_endpoint,
co_endpoint=args.co_endpoint,
lkey=args.lkey
)
site_id = create_cloud_two_site(
auth_token=auth_token,
endpoint=args.ct_endpoint
)
if not site_id:
raise Exception("No site id created.")
cg_id = get_channel_group_id_for_site(
site_id=site_id,
endpoint=args.co_endpoint,
lkey=args.lkey
)
if not cg_id:
raise Exception("No channel group found.")
group_token = add_channels_to_site(
cg_id=cg_id,
channels=channels,
lkey=args.lkey,
endpoint=args.co_endpoint
)
if not group_token:
raise Exception("No channel group token found.")
update_site_group_token(
auth_token=auth_token,
group_token=group_token,
site_id=site_id,
endpoint=args.ct_endpoint
)
for channel in channels:
update_channel_meta(
ch_id=channel,
lkey=args.lkey,
endpoint=args.co_endpoint,
site_id=site_id
)
logging.info("Migration completed.")
if __name__ == "__main__":
main()