Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """ONVIF util."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from zeep.exceptions import Fault
8 
9 
10 def extract_subcodes_as_strings(subcodes: Any) -> list[str]:
11  """Stringify ONVIF subcodes."""
12  if isinstance(subcodes, list):
13  return [code.text if hasattr(code, "text") else str(code) for code in subcodes]
14  return [str(subcodes)]
15 
16 
17 def stringify_onvif_error(error: Exception) -> str:
18  """Stringify ONVIF error."""
19  if isinstance(error, Fault):
20  message = error.message
21  if error.detail is not None: # checking true is deprecated
22  # Detail may be a bytes object, so we need to convert it to string
23  if isinstance(error.detail, bytes):
24  detail = error.detail.decode("utf-8", "replace")
25  else:
26  detail = str(error.detail)
27  message += ": " + detail
28  if error.code is not None: # checking true is deprecated
29  message += f" (code:{error.code})"
30  if error.subcodes is not None: # checking true is deprecated
31  message += (
32  f" (subcodes:{','.join(extract_subcodes_as_strings(error.subcodes))})"
33  )
34  if error.actor:
35  message += f" (actor:{error.actor})"
36  else:
37  message = str(error)
38  return message or f"Device sent empty error with type {type(error)}"
39 
40 
41 def is_auth_error(error: Exception) -> bool:
42  """Return True if error is an authentication error.
43 
44  Most of the tested cameras do not return a proper error code when
45  authentication fails, so we need to check the error message as well.
46  """
47  if not isinstance(error, Fault):
48  return False
49  return (
50  any(
51  "NotAuthorized" in code
52  for code in extract_subcodes_as_strings(error.subcodes)
53  )
54  or "auth" in stringify_onvif_error(error).lower()
55  )
str stringify_onvif_error(Exception error)
Definition: util.py:17
bool is_auth_error(Exception error)
Definition: util.py:41
list[str] extract_subcodes_as_strings(Any subcodes)
Definition: util.py:10