Debian Codegraph @

asusrouter/modules/endpoint/error.py

raw
1 """Error endpoint module.
2
3 This is not an actual endpoint, but rather a module that is used
4 to handle errors from any endpoint.
5 """
6
7 from __future__ import annotations
8
9 from enum import IntEnum
10 import logging
11 from typing import Any
12
13 from asusrouter.const import UNKNOWN_MEMBER, HTTPStatus
14 from asusrouter.error import (
15 AsusRouterAccessError,
16 AsusRouterLogoutError,
17 AsusRouterRequestFormatError,
18 )
19 from asusrouter.modules.endpoint import EndpointType
20 from asusrouter.tools.readers import read_json_content
21
22 _LOGGER = logging.getLogger(__name__)
23
24
25 class AccessError(IntEnum):
26 """Access error enum."""
27
28 UNKNOWN = UNKNOWN_MEMBER
29
30 SUCCESS = HTTPStatus.OK
31
32 NO_ERROR = 0
33 AUTHORIZATION = 2
34 CREDENTIALS = 3
35 TRY_AGAIN = 7
36 LOGOUT = 8
37 ANOTHER = 9
38 CAPTCHA = 10
39 RESET_REQUIRED = 11
40
41
42 def handle_access_error(
43 endpoint: EndpointType, status: Any, headers: Any, content: Any
44 ) -> None:
45 """Handle access errors."""
46
47 # Read the page as json
48 message = read_json_content(content)
49
50 # Get error code
51 error_status = int(message.get("error_status") or UNKNOWN_MEMBER)
52 # Formatting errors
53 if error_status in (
54 HTTPStatus.JSON_BAD_FORMAT,
55 HTTPStatus.JSON_BAD_REQUEST,
56 ):
57 raise AsusRouterRequestFormatError("JSON format error")
58
59 try:
60 error = AccessError(error_status)
61 except ValueError:
62 error = AccessError.UNKNOWN
63
64 # Success
65 if error == AccessError.SUCCESS:
66 return
67
68 _LOGGER.debug("Access error message: %s", message)
69
70 # Additional values
71 attributes: dict[str, Any] = {}
72
73 # Handle logout code (even though it's not an error)
74 if error == AccessError.LOGOUT:
75 raise AsusRouterLogoutError("Session is logged out")
76
77 # Try again later error
78 if error == AccessError.TRY_AGAIN:
79 timeout = message.get("remaining_lock_time")
80 if timeout:
81 attributes["timeout"] = int(timeout)
82
83 # Return
84 raise AsusRouterAccessError(
85 "Access error",
86 error,
87 attributes,
88 )