| 
 | 1 | +import requests  | 
 | 2 | +from typing import Dict, List, Optional, Union  | 
 | 3 | +from reolink_api.alarm import AlarmAPIMixin  | 
 | 4 | +from reolink_api.device import DeviceAPIMixin  | 
 | 5 | +from reolink_api.display import DisplayAPIMixin  | 
 | 6 | +from reolink_api.download import DownloadAPIMixin  | 
 | 7 | +from reolink_api.image import ImageAPIMixin  | 
 | 8 | +from reolink_api.motion import MotionAPIMixin  | 
 | 9 | +from reolink_api.network import NetworkAPIMixin  | 
 | 10 | +from reolink_api.ptz import PtzAPIMixin  | 
 | 11 | +from reolink_api.recording import RecordingAPIMixin  | 
 | 12 | +from reolink_api.resthandle import Request  | 
 | 13 | +from reolink_api.system import SystemAPIMixin  | 
 | 14 | +from reolink_api.user import UserAPIMixin  | 
 | 15 | +from reolink_api.zoom import ZoomAPIMixin  | 
 | 16 | + | 
 | 17 | + | 
 | 18 | +class APIHandler(AlarmAPIMixin,  | 
 | 19 | +                 DeviceAPIMixin,  | 
 | 20 | +                 DisplayAPIMixin,  | 
 | 21 | +                 DownloadAPIMixin,  | 
 | 22 | +                 ImageAPIMixin,  | 
 | 23 | +                 MotionAPIMixin,  | 
 | 24 | +                 NetworkAPIMixin,  | 
 | 25 | +                 PtzAPIMixin,  | 
 | 26 | +                 RecordingAPIMixin,  | 
 | 27 | +                 SystemAPIMixin,  | 
 | 28 | +                 UserAPIMixin,  | 
 | 29 | +                 ZoomAPIMixin):  | 
 | 30 | +    """  | 
 | 31 | +    The APIHandler class is the backend part of the API, the actual API calls  | 
 | 32 | +    are implemented in Mixins.  | 
 | 33 | +    This handles communication directly with the camera.  | 
 | 34 | +    Current camera's tested: RLC-411WS  | 
 | 35 | +
  | 
 | 36 | +    All Code will try to follow the PEP 8 standard as described here: https://www.python.org/dev/peps/pep-0008/  | 
 | 37 | +    """  | 
 | 38 | + | 
 | 39 | +    def __init__(self, ip: str, username: str, password: str, https: bool = False, **kwargs):  | 
 | 40 | +        """  | 
 | 41 | +        Initialise the Camera API Handler (maps api calls into python)  | 
 | 42 | +        :param ip:  | 
 | 43 | +        :param username:  | 
 | 44 | +        :param password:  | 
 | 45 | +        :param proxy: Add a proxy dict for requests to consume.  | 
 | 46 | +        eg: {"http":"socks5://[username]:[password]@[host]:[port], "https": ...}  | 
 | 47 | +        More information on proxies in requests: https://stackoverflow.com/a/15661226/9313679  | 
 | 48 | +        """  | 
 | 49 | +        scheme = 'https' if https else 'http'  | 
 | 50 | +        self.url = f"{scheme}://{ip}/cgi-bin/api.cgi"  | 
 | 51 | +        self.ip = ip  | 
 | 52 | +        self.token = None  | 
 | 53 | +        self.username = username  | 
 | 54 | +        self.password = password  | 
 | 55 | +        Request.proxies = kwargs.get("proxy")  # Defaults to None if key isn't found  | 
 | 56 | + | 
 | 57 | +    def login(self) -> bool:  | 
 | 58 | +        """  | 
 | 59 | +        Get login token  | 
 | 60 | +        Must be called first, before any other operation can be performed  | 
 | 61 | +        :return: bool  | 
 | 62 | +        """  | 
 | 63 | +        try:  | 
 | 64 | +            body = [{"cmd": "Login", "action": 0,  | 
 | 65 | +                     "param": {"User": {"userName": self.username, "password": self.password}}}]  | 
 | 66 | +            param = {"cmd": "Login", "token": "null"}  | 
 | 67 | +            response = Request.post(self.url, data=body, params=param)  | 
 | 68 | +            if response is not None:  | 
 | 69 | +                data = response.json()[0]  | 
 | 70 | +                code = data["code"]  | 
 | 71 | +                if int(code) == 0:  | 
 | 72 | +                    self.token = data["value"]["Token"]["name"]  | 
 | 73 | +                    print("Login success")  | 
 | 74 | +                    return True  | 
 | 75 | +                print(self.token)  | 
 | 76 | +                return False  | 
 | 77 | +            else:  | 
 | 78 | +                # TODO: Verify this change w/ owner. Delete old code if acceptable.  | 
 | 79 | +                #  A this point, response is NoneType. There won't be a status code property.  | 
 | 80 | +                # print("Failed to login\nStatus Code:", response.status_code)  | 
 | 81 | +                print("Failed to login\nResponse was null.")  | 
 | 82 | +                return False  | 
 | 83 | +        except Exception as e:  | 
 | 84 | +            print("Error Login\n", e)  | 
 | 85 | +            raise  | 
 | 86 | + | 
 | 87 | +    def logout(self) -> bool:  | 
 | 88 | +        """  | 
 | 89 | +        Logout of the camera  | 
 | 90 | +        :return: bool  | 
 | 91 | +        """  | 
 | 92 | +        try:  | 
 | 93 | +            data = [{"cmd": "Logout", "action": 0}]  | 
 | 94 | +            self._execute_command('Logout', data)  | 
 | 95 | +            # print(ret)  | 
 | 96 | +            return True  | 
 | 97 | +        except Exception as e:  | 
 | 98 | +            print("Error Logout\n", e)  | 
 | 99 | +            return False  | 
 | 100 | + | 
 | 101 | +    def _execute_command(self, command: str, data: List[Dict], multi: bool = False) -> \  | 
 | 102 | +            Optional[Union[Dict, bool]]:  | 
 | 103 | +        """  | 
 | 104 | +        Send a POST request to the IP camera with given data.  | 
 | 105 | +        :param command: name of the command to send  | 
 | 106 | +        :param data: object to send to the camera (send as json)  | 
 | 107 | +        :param multi: whether the given command name should be added to the  | 
 | 108 | +        url parameters of the request. Defaults to False. (Some multi-step  | 
 | 109 | +        commands seem to not have a single command name)  | 
 | 110 | +        :return: response JSON as python object  | 
 | 111 | +        """  | 
 | 112 | +        params = {"token": self.token, 'cmd': command}  | 
 | 113 | +        if multi:  | 
 | 114 | +            del params['cmd']  | 
 | 115 | +        try:  | 
 | 116 | +            if self.token is None:  | 
 | 117 | +                raise ValueError("Login first")  | 
 | 118 | +            if command == 'Download':  | 
 | 119 | +                # Special handling for downloading an mp4  | 
 | 120 | +                # Pop the filepath from data  | 
 | 121 | +                tgt_filepath = data[0].pop('filepath')  | 
 | 122 | +                # Apply the data to the params  | 
 | 123 | +                params.update(data[0])  | 
 | 124 | +                with requests.get(self.url, params=params, stream=True) as req:  | 
 | 125 | +                    if req.status_code == 200:  | 
 | 126 | +                        with open(tgt_filepath, 'wb') as f:  | 
 | 127 | +                            f.write(req.content)  | 
 | 128 | +                        return True  | 
 | 129 | +                    else:  | 
 | 130 | +                        print(f'Error received: {req.status_code}')  | 
 | 131 | +                        return False  | 
 | 132 | + | 
 | 133 | +            else:  | 
 | 134 | +                response = Request.post(self.url, data=data, params=params)  | 
 | 135 | +                return response.json()  | 
 | 136 | +        except Exception as e:  | 
 | 137 | +            print(f"Command {command} failed: {e}")  | 
 | 138 | +            raise  | 
0 commit comments