File: other.py

package info (click to toggle)
python-ring-doorbell 0.9.13-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 972 kB
  • sloc: python: 4,764; makefile: 14
file content (293 lines) | stat: -rw-r--r-- 9,985 bytes parent folder | download | duplicates (2)
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# vim:sw=4:ts=4:et:
"""Python Ring Other (Intercom) wrapper."""

from __future__ import annotations

import json
import logging
import uuid
from typing import TYPE_CHECKING, Any, ClassVar

from ring_doorbell.const import (
    DOORBELLS_ENDPOINT,
    HEALTH_DOORBELL_ENDPOINT,
    INTERCOM_ALLOWED_USERS,
    INTERCOM_INVITATIONS_DELETE_ENDPOINT,
    INTERCOM_INVITATIONS_ENDPOINT,
    INTERCOM_KINDS,
    INTERCOM_OPEN_ENDPOINT,
    MIC_VOL_MAX,
    MIC_VOL_MIN,
    MSG_VOL_OUTBOUND,
    OTHER_DOORBELL_VOL_MAX,
    OTHER_DOORBELL_VOL_MIN,
    SETTINGS_ENDPOINT,
    VOICE_VOL_MAX,
    VOICE_VOL_MIN,
    RingCapability,
)
from ring_doorbell.exceptions import RingError
from ring_doorbell.generic import RingGeneric

_LOGGER = logging.getLogger(__name__)


class RingOther(RingGeneric):
    """Implementation for Ring Intercom."""

    if TYPE_CHECKING:
        from ring_doorbell.ring import Ring

    def __init__(self, ring: Ring, device_api_id: int, *, shared: bool = False) -> None:
        """Initialise the other devices."""
        super().__init__(ring, device_api_id)
        self.shared = shared

    @property
    def family(self) -> str:
        """Return Ring device family type."""
        return "other"

    async def async_update_health_data(self) -> None:
        """Update health attrs."""
        resp = await self._ring.async_query(
            HEALTH_DOORBELL_ENDPOINT.format(self.device_api_id)
        )
        self._health_attrs = resp.json().get("device_health", {})

    @property
    def model(self) -> str:
        """Return Ring device model name."""
        if self.kind in INTERCOM_KINDS:
            return "Intercom"
        return "Unknown Other"

    def has_capability(self, capability: RingCapability | str) -> bool:
        """Return if device has specific capability."""
        capability = (
            capability
            if isinstance(capability, RingCapability)
            else RingCapability.from_name(capability)
        )
        if capability in [
            RingCapability.OPEN,
            RingCapability.HISTORY,
            RingCapability.DING,
        ]:
            return self.kind in INTERCOM_KINDS
        return False

    @property
    def battery_life(self) -> int | None:
        """Return battery life."""
        if self.kind in INTERCOM_KINDS:
            if self._attrs.get("battery_life") is None:
                return None

            value = int(self._attrs.get("battery_life", 0))
            if value and value > 100:
                value = 100

            return value
        return None

    @property
    def subscribed(self) -> bool:
        """Return if is online."""
        if self.kind in INTERCOM_KINDS:
            result = self._attrs.get("subscribed")
            return result is not None
        return False

    @property
    def has_subscription(self) -> bool:
        """Return boolean if the account has subscription."""
        if self.kind in INTERCOM_KINDS and (features := self._attrs.get("features")):
            return features.get("show_recordings", False)
        return False

    @property
    def unlock_duration(self) -> str | None:
        """Return time unlock switch is held closed."""
        return (
            json.loads(self._attrs["settings"]["intercom_settings"]["config"])
            .get("analog", {})
            .get("unlock_duration")
        )

    @property
    def doorbell_volume(self) -> int:
        """Return doorbell volume."""
        if self.kind in INTERCOM_KINDS:
            return self._attrs["settings"].get("doorbell_volume", 0)
        return 0

    async def async_set_doorbell_volume(self, value: int) -> None:
        """Set the doorbell volume."""
        if not (
            (isinstance(value, int))
            and (OTHER_DOORBELL_VOL_MIN <= value <= OTHER_DOORBELL_VOL_MAX)
        ):
            raise RingError(
                MSG_VOL_OUTBOUND.format(OTHER_DOORBELL_VOL_MIN, OTHER_DOORBELL_VOL_MAX)
            )

        params = {
            "doorbot[settings][doorbell_volume]": str(value),
        }
        url = DOORBELLS_ENDPOINT.format(self.device_api_id)
        await self._ring.async_query(url, extra_params=params, method="PUT")

    @property
    def keep_alive_auto(self) -> float | None:
        """The keep alive auto setting."""
        if self.kind in INTERCOM_KINDS:
            return self._attrs["settings"].get("keep_alive_auto")
        return None

    async def async_set_keep_alive_auto(self, value: float) -> None:
        """Update the keep alive auto setting."""
        url = SETTINGS_ENDPOINT.format(self.device_api_id)
        payload = {"keep_alive_settings": {"keep_alive_auto": value}}

        await self._ring.async_query(url, method="PATCH", json=payload)

    @property
    def mic_volume(self) -> int | None:
        """Return mic volume."""
        if self.kind in INTERCOM_KINDS:
            return self._attrs["settings"].get("mic_volume")
        return None

    async def async_set_mic_volume(self, value: int) -> None:
        """Set the mic volume."""
        if not ((isinstance(value, int)) and (MIC_VOL_MIN <= value <= MIC_VOL_MAX)):
            raise RingError(MSG_VOL_OUTBOUND.format(MIC_VOL_MIN, MIC_VOL_MAX))

        url = SETTINGS_ENDPOINT.format(self.device_api_id)
        payload = {"volume_settings": {"mic_volume": value}}

        await self._ring.async_query(url, method="PATCH", json=payload)

    @property
    def voice_volume(self) -> int | None:
        """Return voice volume."""
        if self.kind in INTERCOM_KINDS:
            return self._attrs["settings"].get("voice_volume")
        return None

    async def async_set_voice_volume(self, value: int) -> None:
        """Set the voice volume."""
        if not ((isinstance(value, int)) and (VOICE_VOL_MIN <= value <= VOICE_VOL_MAX)):
            raise RingError(MSG_VOL_OUTBOUND.format(VOICE_VOL_MIN, VOICE_VOL_MAX))

        url = SETTINGS_ENDPOINT.format(self.device_api_id)
        payload = {"volume_settings": {"voice_volume": value}}

        await self._ring.async_query(url, method="PATCH", json=payload)

    async def async_get_clip_length_max(self) -> int | None:
        """Get the Maximum clip length."""
        url = SETTINGS_ENDPOINT.format(self.device_api_id)
        resp = await self._ring.async_query(url, method="GET")
        return resp.json().get("video_settings", {}).get("clip_length_max")

    async def async_set_clip_length_max(self, value: int) -> None:
        """Set the maximum clip length.

        This value sets an effective refractory period on consecutive rigns
        eg if set to default value of 60, rings occuring with 60 seconds of
        first will not be detected.
        """
        url = SETTINGS_ENDPOINT.format(self.device_api_id)
        payload = {"video_settings": {"clip_length_max": value}}
        await self._ring.async_query(url, method="PATCH", json=payload)

    @property
    def connection_status(self) -> str | None:
        """Return connection status."""
        if self.kind in INTERCOM_KINDS:
            return self._attrs.get("alerts", {}).get("connection")
        return None

    async def async_get_allowed_users(self) -> list[dict[str, Any]] | None:
        """Return list of users allowed or invited to access."""
        if self.kind in INTERCOM_KINDS:
            url = INTERCOM_ALLOWED_USERS.format(self.location_id)
            resp = await self._ring.async_query(url, method="GET")
            return resp.json()

        return None

    async def async_open_door(self, user_id: int = -1) -> bool:
        """Open the door."""
        if self.kind in INTERCOM_KINDS:
            url = INTERCOM_OPEN_ENDPOINT.format(self.device_api_id)
            request_id = str(uuid.uuid4())
            # params can also accept:
            # issue_time: in seconds
            # command_timeout: in seconds
            payload = {
                "command_name": "device_rpc",
                "request": {
                    "id": request_id,
                    "jsonrpc": "2.0",
                    "method": "unlock_door",
                    "params": {
                        "door_id": 0,
                        "user_id": user_id,
                    },
                },
            }
            resp = await self._ring.async_query(url, method="PUT", json=payload)
            response = resp.json()
            if response.get("result", {}).get("code", -1) == 0:
                return True

        return False

    async def async_invite_access(self, email: str) -> bool:
        """Invite user."""
        if self.kind in INTERCOM_KINDS:
            url = INTERCOM_INVITATIONS_ENDPOINT.format(self.location_id)
            payload = {
                "invitation": {
                    "doorbot_ids": [self.device_api_id],
                    "invited_email": email,
                    "group_ids": [],
                }
            }
            await self._ring.async_query(url, method="POST", json=payload)
            return True

        return False

    async def async_remove_access(self, user_id: int) -> bool:
        """Remove user access or invitation."""
        if self.kind in INTERCOM_KINDS:
            url = INTERCOM_INVITATIONS_DELETE_ENDPOINT.format(self.location_id, user_id)
            await self._ring.async_query(url, method="DELETE")
            return True

        return False

    DEPRECATED_API_QUERIES: ClassVar = {
        *RingGeneric.DEPRECATED_API_QUERIES,
        "update_health_data",
        "open_door",
        "invite_access",
        "remove_access",
    }
    DEPRECATED_API_PROPERTY_GETTERS: ClassVar = {
        *RingGeneric.DEPRECATED_API_PROPERTY_GETTERS,
        "clip_length_max",
        "allowed_users",
    }
    DEPRECATED_API_PROPERTY_SETTERS: ClassVar = {
        *RingGeneric.DEPRECATED_API_PROPERTY_SETTERS,
        "doorbell_volume",
        "keep_alive_auto",
        "mic_volume",
        "voice_volume",
        "clip_length_max",
    }