Skip to content

Commit

Permalink
Improved exceptions, fixed pylint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
RenierM26 committed Mar 7, 2021
1 parent 8665a6c commit b13d090
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 48 deletions.
4 changes: 3 additions & 1 deletion pyezviz/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ def status(self):
"encrypted": bool(self._device.get("statusInfos").get("isEncrypted")),
"local_ip": self.local_ip(),
"wan_ip": self._device.get("connectionInfos", {}).get("netIp", "0.0.0.0"),
"local_rtsp_port": self._device.get("connectionInfos").get("localRtspPort"),
"local_rtsp_port": self._device.get("connectionInfos").get(
"localRtspPort", "554"
),
"supported_channels": self._device.get("deviceInfos").get("channelNumber"),
"detection_sensibility": self.detection_sensibility(),
"battery_level": self._device.get("statusInfos")
Expand Down
146 changes: 100 additions & 46 deletions pyezviz/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Ezviz API."""
import hashlib
import json
import logging
from random import randint
from uuid import uuid4
Expand All @@ -27,7 +26,7 @@
API_ENDPOINT_SWITCH_DEFENCE_MODE = "/v3/userdevices/v1/group/switchDefenceMode"
API_ENDPOINT_SWITCH_SOUND_ALARM = "/sendAlarm"

DEFAULT_TIMEOUT = 15
DEFAULT_TIMEOUT = 25
MAX_RETRIES = 3


Expand Down Expand Up @@ -79,40 +78,51 @@ def _login(self):
timeout=self._timeout,
)

req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Can not login to API") from err

try:
json_result = req.json()

if self._session.cookies.get("REDIRECTCOOKIE", domain=API_BASE_TLD):
print(f"Your region is incorrect!")
self._login_api()
except ValueError as err:
raise PyEzvizError("Can't decode response") from err

if json_result["retcode"] == "1001":
raise PyEzvizError("Incorrect login details")
if self._session.cookies.get("REDIRECTCOOKIE", domain=API_BASE_TLD):
print("Your region is incorrect!")
self._login_api()

if json_result["retcode"] == "1002":
raise PyEzvizError("Login error: Captcha required")
if json_result["retcode"] == "1001":
raise PyEzvizError("Incorrect login details")

if json_result["retcode"] == "1005":
raise PyEzvizError("Login error: Incorrect Captcha code")
if json_result["retcode"] == "1002":
raise PyEzvizError("Login error: Captcha required")

# Update cookie with JS Session ID that is generated by website.
if json_result["retcode"] == "1005":
raise PyEzvizError("Login error: Incorrect Captcha code")

if req.status_code != 200:
raise PyEzvizError(
f"Login error: Please check your username/password: {req.text} "
)

# Update cookie with JS Session ID that is generated by website.
try:
req = self._session.get(
"https://" + self.api_domain + API_BASE_TLD + "/check_plugin.jsp",
timeout=self._timeout,
)

req.raise_for_status()

self._csrf_token = self._session.cookies.get(
"AS_SessionID", domain=self.api_domain + API_BASE_TLD
)

except OSError as err:
except requests.HTTPError as err:
raise PyEzvizError("Can not login to API") from err

if req.status_code != 200:
raise PyEzvizError(
f"Login error: Please check your username/password: {req.text} "
)

return True

def _login_api(self):
Expand All @@ -137,13 +147,15 @@ def _login_api(self):
timeout=self._timeout,
)

req.raise_for_status()

json_result = req.json()

if json_result["meta"]["code"] == 1100:
region = json_result["loginArea"]["apiDomain"]
raise PyEzvizError(f"region url: {region} ")

except OSError as err:
except requests.HTTPError as err:
raise PyEzvizError("Can not login to API") from err

if req.status_code != 200:
Expand All @@ -169,7 +181,9 @@ def _api_get_pagelist(self, page_filter=None, json_key=None, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401:
Expand All @@ -183,7 +197,8 @@ def _api_get_pagelist(self, page_filter=None, json_key=None, max_retries=0):

try:
json_output = req.json()
except (OSError, json.decoder.JSONDecodeError) as err:

except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -233,7 +248,9 @@ def get_alarminfo(self, serial, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401 or req.status_code == 302:
Expand All @@ -249,7 +266,8 @@ def get_alarminfo(self, serial, max_retries=0):

try:
json_output = req.json()
except (OSError, json.decoder.JSONDecodeError) as err:

except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -281,7 +299,9 @@ def _switch_status(self, serial, status_type, enable, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401 or req.status_code == 302:
Expand All @@ -295,7 +315,7 @@ def _switch_status(self, serial, status_type, enable, max_retries=0):
try:
json_output = req.json()

except (OSError, json.decoder.JSONDecodeError) as err:
except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -328,7 +348,9 @@ def sound_alarm(self, serial, enable=1, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401 or req.status_code == 302:
Expand All @@ -342,7 +364,7 @@ def sound_alarm(self, serial, enable=1, max_retries=0):
try:
json_output = req.json()

except (OSError, json.decoder.JSONDecodeError) as err:
except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -402,7 +424,7 @@ def _get_all_device_infos(self):
devices = self._get_page_list()
result = {}

for idx, device in enumerate(devices["deviceInfos"]):
for device in devices["deviceInfos"]:
result[device["deviceSerial"]] = {}
result[device["deviceSerial"]]["deviceInfos"] = device
result[device["deviceSerial"]]["connectionInfos"] = devices.get(
Expand Down Expand Up @@ -447,7 +469,7 @@ def get_all_per_serial_infos(self, serial=None):
devices = self._get_page_list()
result = {serial: {}}

for idx, device in enumerate(devices["deviceInfos"]):
for device in devices["deviceInfos"]:
if device["deviceSerial"] == serial:
result[device["deviceSerial"]]["deviceInfos"] = device
result[device["deviceSerial"]]["deviceInfos"] = device
Expand Down Expand Up @@ -511,7 +533,9 @@ def ptz_control(self, command, serial, action, speed=5):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

return req.text
Expand All @@ -529,7 +553,9 @@ def login(self):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError(
"Could not access Ezviz login check API: " + str(err)
) from err
Expand All @@ -538,10 +564,14 @@ def login(self):
# session is wrong, need to relogin
self._login()

else:
try:
response_json = req.json()
if response_json["success"] != "success":
self._login()

except ValueError as err:
raise PyEzvizError("Can't decode response" + str(err)) from err

if response_json["success"] != "success":
self._login()

return True

Expand All @@ -562,7 +592,9 @@ def data_report(self, serial, enable=1, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401 or req.status_code == 302:
Expand All @@ -576,7 +608,7 @@ def data_report(self, serial, enable=1, max_retries=0):
try:
json_output = req.json()

except (OSError, json.decoder.JSONDecodeError) as err:
except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -617,7 +649,9 @@ def api_set_defence_schedule(self, serial, schedule, enable, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code != 200:
Expand All @@ -631,7 +665,7 @@ def api_set_defence_schedule(self, serial, schedule, enable, max_retries=0):
try:
json_output = req.json()

except (OSError, json.decoder.JSONDecodeError) as err:
except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -664,7 +698,9 @@ def api_set_defence_mode(self, mode: DefenseModeType, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code != 200:
Expand All @@ -676,7 +712,7 @@ def api_set_defence_mode(self, mode: DefenseModeType, max_retries=0):
try:
json_output = req.json()

except (OSError, json.decoder.JSONDecodeError) as err:
except ValueError as err:
raise PyEzvizError(
"Impossible to decode response: "
+ str(err)
Expand Down Expand Up @@ -716,7 +752,9 @@ def detection_sensibility(self, serial, sensibility=3, type_value=3, max_retries
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401:
Expand All @@ -727,7 +765,12 @@ def detection_sensibility(self, serial, sensibility=3, type_value=3, max_retries
serial, sensibility, type_value, max_retries + 1
)

response_json = req.json()
try:
response_json = req.json()

except ValueError as err:
raise PyEzvizError("Could not decode response:" + str(err)) from err

if response_json["resultCode"] and response_json["resultCode"] != "0":
return "Unknown value"

Expand All @@ -750,7 +793,9 @@ def get_detection_sensibility(self, serial, type_value="0", max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401:
Expand All @@ -759,7 +804,11 @@ def get_detection_sensibility(self, serial, type_value="0", max_retries=0):
logging.info("Got 401, relogging (max retries: %s)", str(max_retries))
return self.get_detection_sensibility(serial, type_value, max_retries + 1)

response_json = req.json()
try:
response_json = req.json()

except ValueError as err:
raise PyEzvizError("Could not decode response:" + str(err)) from err

if response_json["resultCode"] != "0":
return "Unknown"
Expand Down Expand Up @@ -799,7 +848,9 @@ def alarm_sound(self, serial, sound_type, enable=1, max_retries=0):
timeout=self._timeout,
)

except OSError as err:
req.raise_for_status()

except requests.HTTPError as err:
raise PyEzvizError("Could not access Ezviz' API: " + str(err)) from err

if req.status_code == 401:
Expand All @@ -819,7 +870,10 @@ def switch_status(self, serial, status_type, enable=0):
def _get_page_list(self):
"""Get ezviz device info broken down in sections."""
return self._api_get_pagelist(
page_filter="CLOUD, TIME_PLAN, CONNECTION, SWITCH, STATUS, WIFI, NODISTURB, KMS, P2P, TIME_PLAN, CHANNEL, VTM, DETECTOR, FEATURE, UPGRADE, VIDEO_QUALITY, QOS",
page_filter="CLOUD, TIME_PLAN, CONNECTION, SWITCH,"
"STATUS, WIFI, NODISTURB, KMS, P2P,"
"TIME_PLAN, CHANNEL, VTM, DETECTOR,"
"FEATURE, UPGRADE, VIDEO_QUALITY, QOS",
json_key=None,
)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name='pyezviz',
version="0.1.7.5",
version="0.1.7.6",
license='Apache Software License 2.0',
author='Pierre Ourdouille',
author_email='[email protected]',
Expand Down

0 comments on commit b13d090

Please sign in to comment.