-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate_gateway_channels_from_csv.py
More file actions
215 lines (183 loc) · 6.2 KB
/
create_gateway_channels_from_csv.py
File metadata and controls
215 lines (183 loc) · 6.2 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
import argparse
import re
import os
import logging
from urllib.parse import urlparse, urljoin
from dataclasses import dataclass
from typing import Any, Dict
from enum import Enum
import requests
@dataclass
class ChannelParams:
name: str
timezone: str
ip: str
user: str
password: str
rtsp: int
http: int
def parse_line(line: str) -> ChannelParams:
"""
Parse line from CSV file and create Channel object
line format: name,location,group,user,password,serial,mac
param[0] - Camera name
param[1] - Timezone
param[2] - Local IP
param[3] - Username
param[4] - Password
param[5] - HTTP Port
param[6] - RTSP Port
"""
line = line.replace('\n', '')
param = line.split(",")
return ChannelParams(
name=param[0],
timezone=param[1],
ip=param[2],
user=param[3],
password=param[4],
http=int(param[5]),
rtsp=int(param[6])
)
def get_headers(token: str) -> Dict[str, str]:
return {
"accept": "application/json",
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def get_cloud_two_info(email: str, password: str, endpoint: str):
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 VMS Endpoint: %s", resp["session"]["company"]["endpoint"])
# logging.info("Received VMS LKey: %s", resp["session"]["company"]["lKey"])
return {
"access_token": resp["accessToken"],
"vms_endpoint": resp["session"]["company"]["endpoint"],
# "lkey": resp["session"]["company"]["lKey"]
}
def get_gateway_info(endpoint: str, auth_token: str, guid: str, mac=None):
# /v1/gateway
api_endpoint = f"https://{endpoint}/v1/gateway?params=%7B%22include_meta%22%3A%20true%7D"
gw_request = requests.get(
url=api_endpoint,
headers=get_headers(token=auth_token),
timeout=10
)
if gw_request.status_code != 200:
logging.error("Failed to request gateways.")
return {}
# gateway = {}
for curr_gateway in gw_request.json()["objects"]:
if guid and not mac and guid == curr_gateway["meta"]["gateway_id"]:
# gateway = curr_gateway
return curr_gateway
elif guid and mac and "gateway_mac" in curr_gateway["meta"]:
if (
guid == curr_gateway["meta"]["gateway_id"] and
mac == curr_gateway["meta"]["gateway_mac"]
):
return curr_gateway
return {}
def add_camera_to_gw(endpoint, auth_token, channel_params: ChannelParams, gateway: Dict):
api_endpoint = f"https://{endpoint}/v1/gateway/{gateway['id']}/camera"
body = {
"name": channel_params.name,
"timezone": channel_params.timezone,
"meta": {
"siteId": gateway["meta"]["siteId"],
gateway["meta"]["siteId"]: "siteId"
},
"url": channel_params.ip,
"http": channel_params.http,
"rtsp": channel_params.rtsp,
"username": channel_params.user,
"password": channel_params.password
}
if "openwrt" in gateway["meta"]:
body["guuid"] = ""
body["serialNumber"] = gateway["meta"]["gateway_id"]
else:
body["guuid"] = gateway["meta"]["gateway_id"]
gw_request = requests.post(
url=api_endpoint,
headers=get_headers(token=auth_token),
json=body,
timeout=10
)
if gw_request.status_code != 201:
logging.error(
f"Failed to add camera. Name: {channel_params.name}, IP: {channel_params.ip}"
)
else:
logging.info(
f"Successfully added camera with ID {gw_request.json()['id']}"
)
def main():
logging.basicConfig(
format="%(asctime)s %(filename)s %(levelname)s: %(message)s",
level=os.environ.get("LOGGING", "INFO"),
)
parser = argparse.ArgumentParser(description="")
parser.add_argument("--email", help="Email for cloudtwo account", required=True)
parser.add_argument("--password", help="Password for cloudtwo account", required=True)
parser.add_argument("--csv", help="Path to CSV file", required=True)
parser.add_argument("--endpoint", help="Cloudtwo API endpoint", required=True)
parser.add_argument("--guid", help="Unique ID of docker gateway", default=None)
parser.add_argument("--serial", help="Serial number of Openwrt gateway", default=None)
parser.add_argument("--mac", help="MAC Address of Openwrt gateway", default=None)
args = parser.parse_args()
# Get Cloud Two info
c2_dict = get_cloud_two_info(
email=args.email,
password=args.password,
endpoint=args.endpoint
)
if not c2_dict:
raise Exception("No auth_token.")
else:
auth_token = c2_dict["access_token"]
if not args.mac and not args.serial and args.guid:
gateway = get_gateway_info(
endpoint=args.endpoint,
auth_token=auth_token,
guid=args.guid
)
elif not args.guid and args.mac and args.serial:
gateway = get_gateway_info(
endpoint=args.endpoint,
auth_token=auth_token,
guid=args.serial,
mac=args.mac
)
else:
raise Exception("Invalid combination of gateway values.")
if not gateway:
raise Exception("Gateway not found.")
with (
open(args.csv, "r", encoding="utf-8") as file,
):
lines = file.readlines()
for line in lines:
channel_params = parse_line(line)
logging.info(f"Channel_params: {channel_params}")
add_camera_to_gw(
endpoint=args.endpoint,
auth_token=auth_token,
channel_params=channel_params,
gateway=gateway
)
if __name__ == "__main__":
main()