python-ring 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python_ring/cli.py ADDED
@@ -0,0 +1,977 @@
1
+ # vim:sw=4:ts=4:et
2
+ # Many thanks to @troopermax <https://github.com/troopermax>
3
+ """Python Ring command line interface."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import functools
9
+ import getpass
10
+ import json
11
+ import logging
12
+ import select
13
+ import sys
14
+ from contextlib import asynccontextmanager
15
+ from datetime import datetime
16
+ from pathlib import Path, PurePath
17
+ from typing import Sequence, cast, TypeVar, NoReturn
18
+
19
+ import asyncclick as click
20
+
21
+ from python_ring import (
22
+ Auth,
23
+ AuthenticationError,
24
+ Requires2FAError,
25
+ Ring,
26
+ RingDoorBell,
27
+ RingEvent,
28
+ RingGeneric,
29
+ RingStickUpCam,
30
+ RingOther,
31
+ RingCapability,
32
+ )
33
+ from python_ring.const import (
34
+ CLI_TOKEN_FILE,
35
+ GCM_TOKEN_FILE,
36
+ PACKAGE_NAME,
37
+ USER_AGENT,
38
+ DOORBELL_EXISTING_TYPE,
39
+ )
40
+
41
+
42
+ def _header() -> None:
43
+ _bar()
44
+ echo("Ring CLI")
45
+
46
+
47
+ def _bar() -> None:
48
+ echo("---------------------------------")
49
+
50
+
51
+ def error(msg: str) -> NoReturn:
52
+ """Print an error and exit."""
53
+ echo(msg)
54
+ sys.exit(1)
55
+
56
+
57
+ click.anyio_backend = "asyncio" # type: ignore[attr-defined]
58
+
59
+ pass_ring = click.make_pass_decorator(Ring)
60
+ pass_doorbell = click.make_pass_decorator(RingDoorBell)
61
+
62
+ cache_file = Path(CLI_TOKEN_FILE)
63
+ gcm_cache_file = Path(GCM_TOKEN_FILE)
64
+
65
+
66
+ def CatchAllExceptions(cls):
67
+ """Capture all exceptions and prints them nicely.
68
+
69
+ Idea from https://stackoverflow.com/a/44347763 and
70
+ https://stackoverflow.com/questions/52213375
71
+ """
72
+
73
+ def _handle_exception(debug, exc):
74
+ if isinstance(exc, click.ClickException):
75
+ raise
76
+ # Handle exit request from click.
77
+ if isinstance(exc, click.exceptions.Exit):
78
+ sys.exit(exc.exit_code)
79
+ echo(f"Raised error: {exc}")
80
+ if debug:
81
+ raise
82
+ echo("Run with --debug enabled to see stacktrace")
83
+ sys.exit(1)
84
+
85
+ class _CommandCls(cls):
86
+ _debug = False
87
+
88
+ async def make_context(self, info_name, args, parent=None, **extra):
89
+ self._debug = any(
90
+ [arg for arg in args if arg in ["--debug", "-d", "--verbose", "-v"]]
91
+ )
92
+ try:
93
+ return await super().make_context(
94
+ info_name, args, parent=parent, **extra
95
+ )
96
+ except Exception as exc:
97
+ _handle_exception(self._debug, exc)
98
+
99
+ async def invoke(self, ctx):
100
+ try:
101
+ return await super().invoke(ctx)
102
+ except asyncio.CancelledError:
103
+ pass
104
+ except KeyboardInterrupt:
105
+ echo("Cli interrupted with keyboard interrupt")
106
+ except Exception as exc:
107
+ _handle_exception(self._debug, exc)
108
+
109
+ return _CommandCls
110
+
111
+
112
+ class MutuallyExclusiveOption(click.Option):
113
+ """Prevents incompatable options being supplied, i.e. on and off."""
114
+
115
+ def __init__(self, *args, **kwargs) -> None:
116
+ self.mutually_exclusive = set(kwargs.pop("mutually_exclusive", []))
117
+ _help = kwargs.get("help", "")
118
+ if self.mutually_exclusive:
119
+ ex_str = ", ".join(self.mutually_exclusive)
120
+ kwargs["help"] = _help + (
121
+ " NOTE: This argument is mutually exclusive with "
122
+ " arguments: [" + ex_str + "]."
123
+ )
124
+ super().__init__(*args, **kwargs)
125
+
126
+ async def handle_parse_result(self, ctx, opts, args):
127
+ if self.mutually_exclusive.intersection(opts) and self.name in opts:
128
+ msg = (
129
+ "Illegal usage: `{}` is mutually exclusive with arguments `{}`.".format(
130
+ self.name, ", ".join(self.mutually_exclusive)
131
+ )
132
+ )
133
+ raise click.UsageError(msg)
134
+
135
+ return await super().handle_parse_result(ctx, opts, args)
136
+
137
+
138
+ echo = click.echo
139
+
140
+
141
+ def token_updated(token) -> None:
142
+ """Writes token to file."""
143
+ cache_file.write_text(json.dumps(token), encoding="utf-8")
144
+
145
+
146
+ def _format_filename(device_name, event):
147
+ if not isinstance(event, dict):
148
+ return None
149
+
150
+ answered_status = "answered" if event["answered"] else "not_answered"
151
+
152
+ filename = "{}_{}_{}_{}_{}".format(
153
+ device_name, event["created_at"], event["kind"], answered_status, event["id"]
154
+ )
155
+
156
+ return filename.replace(" ", "_").replace(":", ".") + ".mp4"
157
+
158
+
159
+ async def _do_auth(username, password, user_agent=USER_AGENT):
160
+ if not username:
161
+ username = input("Username: ")
162
+
163
+ if not password:
164
+ password = getpass.getpass("Password: ")
165
+
166
+ auth = Auth(user_agent, None, token_updated)
167
+ try:
168
+ await auth.async_fetch_token(username, password)
169
+ return auth
170
+ except Requires2FAError:
171
+ await auth.async_fetch_token(username, password, input("2FA Code: "))
172
+ return auth
173
+
174
+
175
+ async def _get_ring(username, password, do_update_data, user_agent=USER_AGENT):
176
+ # connect to Ring account
177
+ global cache_file, gcm_cache_file
178
+ if user_agent != USER_AGENT:
179
+ cache_file = Path(user_agent + ".token.cache")
180
+ gcm_cache_file = Path(user_agent + ".gcm_token.cache")
181
+ if cache_file.is_file():
182
+ auth = Auth(
183
+ user_agent,
184
+ json.loads(cache_file.read_text(encoding="utf-8")),
185
+ token_updated,
186
+ )
187
+ ring = Ring(auth)
188
+ do_method = (
189
+ ring.async_update_data if do_update_data else ring.async_create_session
190
+ )
191
+ try:
192
+ await do_method()
193
+ except AuthenticationError:
194
+ auth = await _do_auth(username, password)
195
+ ring = Ring(auth)
196
+ do_method = (
197
+ ring.async_update_data if do_update_data else ring.async_create_session
198
+ )
199
+ await do_method()
200
+ else:
201
+ auth = await _do_auth(username, password, user_agent=user_agent)
202
+ ring = Ring(auth)
203
+ do_method = (
204
+ ring.async_update_data if do_update_data else ring.async_create_session
205
+ )
206
+ await do_method()
207
+
208
+ return ring
209
+
210
+
211
+ _T = TypeVar("_T")
212
+
213
+
214
+ def _get_device(
215
+ ring: Ring,
216
+ device_families: list[str],
217
+ device_type: type[_T],
218
+ device_name: str | None = None,
219
+ *,
220
+ device_description: str | None = None,
221
+ ) -> _T:
222
+ description = (
223
+ device_description if device_description else " or ".join(device_families)
224
+ )
225
+ if not device_name:
226
+ dev_dict: dict[int, RingGeneric] = {}
227
+ devices = ring.devices()
228
+ for device_family in device_families:
229
+ for dev in devices[device_family]:
230
+ dev_dict[dev.device_api_id] = dev
231
+ devs = list(dev_dict.values())
232
+ found = len(dev_dict)
233
+ if found == 1:
234
+ return cast(_T, devs[0])
235
+ elif found == 0:
236
+ error(f"No {description} found")
237
+ else:
238
+ error(
239
+ f"There are {found} {description}s, you need to pass the --device-name option."
240
+ )
241
+ elif device := ring.get_device_by_name(device_name):
242
+ if device.family in device_families and isinstance(device, device_type):
243
+ return device
244
+ else:
245
+ error(f"{device_name} is not a {description}")
246
+ else:
247
+ error(f"Cannot find {description} with name {device_name}")
248
+
249
+
250
+ @click.group(
251
+ invoke_without_command=True,
252
+ cls=CatchAllExceptions(click.Group),
253
+ )
254
+ @click.version_option(package_name="python_ring")
255
+ @click.option(
256
+ "--username",
257
+ default=None,
258
+ required=False,
259
+ envvar="RING_USERNAME",
260
+ help="Username for Ring account.",
261
+ )
262
+ @click.option(
263
+ "--password",
264
+ default=None,
265
+ required=False,
266
+ envvar="RING_PASSWORD",
267
+ help="Password for Ring account",
268
+ )
269
+ @click.option("-d", "--debug", default=False, is_flag=True)
270
+ @click.option(
271
+ "--user-agent",
272
+ default=USER_AGENT,
273
+ required=False,
274
+ envvar="RING_USER_AGENT",
275
+ help="User agent to send to ring",
276
+ )
277
+ @click.pass_context
278
+ async def cli(ctx, username, password, debug, user_agent):
279
+ """Command line function."""
280
+ # no need to perform any checks if we are just displaying the help
281
+ if "--help" in sys.argv:
282
+ # Context object is required to avoid crashing on sub-groups
283
+ ctx.obj = Ring(None)
284
+ return
285
+ _header()
286
+
287
+ logging.basicConfig()
288
+ log_level = logging.DEBUG if debug else logging.INFO
289
+ logger = logging.getLogger(PACKAGE_NAME)
290
+ logger.setLevel(log_level)
291
+
292
+ logger = logging.getLogger("firebase_messaging")
293
+ logger.setLevel(log_level)
294
+
295
+ no_update_commands = ["listen"]
296
+ no_update = ctx.invoked_subcommand in no_update_commands
297
+
298
+ @asynccontextmanager
299
+ async def async_wrapped_ring(ring: Ring):
300
+ try:
301
+ yield ring
302
+ finally:
303
+ await ring.auth.async_close()
304
+
305
+ ring = await _get_ring(username, password, not no_update, user_agent)
306
+ # wrapped ring will ensure async_close is called when cli is finished
307
+ ctx.obj = await ctx.with_async_resource(async_wrapped_ring(ring))
308
+
309
+ if ctx.invoked_subcommand is None:
310
+ return await ctx.invoke(show)
311
+ return None
312
+
313
+
314
+ @cli.command(name="list")
315
+ @pass_ring
316
+ async def list_command(ring: Ring) -> None:
317
+ """List ring devices."""
318
+ devices = ring.devices()
319
+ device: RingGeneric | None = None
320
+ for device in devices.doorbots:
321
+ echo(device)
322
+ for device in devices.authorized_doorbots:
323
+ echo(device)
324
+ for device in devices.chimes:
325
+ echo(device)
326
+ for device in devices.stickup_cams:
327
+ echo(device)
328
+ for device in devices.other:
329
+ echo(device)
330
+
331
+
332
+ @cli.command()
333
+ @pass_ring
334
+ @click.pass_context
335
+ @click.option(
336
+ "--on",
337
+ "turn_on",
338
+ cls=MutuallyExclusiveOption,
339
+ is_flag=True,
340
+ default=None,
341
+ required=False,
342
+ mutually_exclusive=["--off"],
343
+ )
344
+ @click.option(
345
+ "--off",
346
+ "turn_off",
347
+ cls=MutuallyExclusiveOption,
348
+ is_flag=True,
349
+ default=None,
350
+ required=False,
351
+ mutually_exclusive=["--on"],
352
+ )
353
+ @click.option(
354
+ "--device-name",
355
+ "-dn",
356
+ required=True,
357
+ default=None,
358
+ help="Name of the ring device",
359
+ )
360
+ async def motion_detection(ctx, ring: Ring, device_name, turn_on, turn_off):
361
+ """Get and change the motion detecton status of a device."""
362
+ device = ring.get_device_by_name(device_name)
363
+
364
+ if not device:
365
+ echo(
366
+ f"No device with name {device_name} found."
367
+ + " List of found device names (kind) is:"
368
+ )
369
+ return await ctx.invoke(list_command)
370
+ if not device.has_capability("motion_detection"):
371
+ echo(f"{device!s} is not capable of motion detection")
372
+ return None
373
+ device = cast(RingDoorBell, device)
374
+ state = "on" if device.motion_detection else "off"
375
+ if not turn_on and not turn_off:
376
+ echo(f"{device!s} has motion detection {state}")
377
+ return None
378
+ is_on = device.motion_detection
379
+ if (turn_on and is_on) or (turn_off and not is_on):
380
+ echo(f"{device!s} already has motion detection {state}")
381
+ return None
382
+
383
+ await device.async_set_motion_detection(turn_on if turn_on else False)
384
+ await ring.async_update_devices()
385
+ state = "on" if device.motion_detection else "off"
386
+ echo(f"{device!s} motion detection set to {state}")
387
+ return None
388
+
389
+
390
+ @cli.command()
391
+ @pass_ring
392
+ @click.pass_context
393
+ @click.argument("enable", type=click.BOOL, default=None, required=False)
394
+ @click.option(
395
+ "--device-name",
396
+ "-dn",
397
+ required=True,
398
+ default=None,
399
+ help="Name of the ring device",
400
+ )
401
+ async def light(ctx, ring: Ring, device_name, enable):
402
+ """Get and change the light state of a device."""
403
+ device = ring.get_device_by_name(device_name)
404
+
405
+ if not device:
406
+ echo(
407
+ f"No device with name {device_name} found."
408
+ + " List of found device names (kind) is:"
409
+ )
410
+ return await ctx.invoke(list_command)
411
+ if not device.has_capability(RingCapability.LIGHT):
412
+ echo(f"{device!s} does not have a light")
413
+ return None
414
+ device = cast(RingStickUpCam, device)
415
+ state = "on" if device.light else "off"
416
+ if enable is None:
417
+ echo(f"{device!s} light is {state}")
418
+ return None
419
+ is_on = device.light
420
+ if (enable and is_on) or (not enable and not is_on):
421
+ echo(f"{device!s} light is already {state}")
422
+ return None
423
+
424
+ await device.async_set_light(enable)
425
+ await ring.async_update_devices()
426
+ state = "on" if device.light else "off"
427
+ echo(f"{device!s} light set to {state}")
428
+ return None
429
+
430
+
431
+ @cli.command()
432
+ @click.option(
433
+ "--device-name",
434
+ "-dn",
435
+ required=False,
436
+ default=None,
437
+ help="Name of device, if ommited shows all devices",
438
+ )
439
+ @pass_ring
440
+ @click.pass_context
441
+ async def show(ctx, ring: Ring, device_name):
442
+ """Display ring devices."""
443
+ devices: Sequence[RingGeneric] | None = None
444
+
445
+ if device_name and (device := ring.get_device_by_name(device_name)):
446
+ devices = [device]
447
+ elif device_name:
448
+ echo(
449
+ f"No device with name {device_name} found. "
450
+ + "List of found device names (kind) is:"
451
+ )
452
+ return await ctx.invoke(list_command)
453
+ else:
454
+ devices = ring.get_device_list()
455
+
456
+ for dev in devices:
457
+ await dev.async_update_health_data()
458
+ echo("Name: %s" % dev.name)
459
+ echo("Family: %s" % dev.family)
460
+ echo("ID: %s" % dev.id)
461
+ echo("Timezone: %s" % dev.timezone)
462
+ echo("Wifi Name: %s" % dev.wifi_name)
463
+ echo("Wifi RSSI: %s" % dev.wifi_signal_strength)
464
+ echo()
465
+ return None
466
+
467
+
468
+ @cli.command(name="devices")
469
+ @click.option(
470
+ "--device-name",
471
+ "-dn",
472
+ required=False,
473
+ default=None,
474
+ help="Name of device, if ommited shows all devices",
475
+ )
476
+ @click.option(
477
+ "--json",
478
+ "json_flag",
479
+ required=False,
480
+ is_flag=True,
481
+ help="Output raw json",
482
+ )
483
+ @pass_ring
484
+ @click.pass_context
485
+ async def devices_command(ctx, ring: Ring, device_name, json_flag):
486
+ """Get device information."""
487
+ if not json_flag:
488
+ echo(
489
+ "(Pretty format coming soon, if you want json consistently "
490
+ + "from this command provide the --json flag)"
491
+ )
492
+ device_json = None
493
+ if device_name and (device := ring.get_device_by_name(device_name)):
494
+ device_json = ring.devices_data[device.family][device.id]
495
+ elif device_name:
496
+ echo(
497
+ f"No device with name {device_name} found. "
498
+ + "List of found device names (kind) is:"
499
+ )
500
+ return await ctx.invoke(list_command)
501
+
502
+ if device_json:
503
+ echo(json.dumps(device_json, indent=2))
504
+ return None
505
+ else:
506
+ for device_type in ring.devices_data:
507
+ for device_api_id in ring.devices_data[device_type]:
508
+ echo(
509
+ json.dumps(ring.devices_data[device_type][device_api_id], indent=2)
510
+ )
511
+ return None
512
+
513
+
514
+ @cli.command()
515
+ @click.option(
516
+ "--json",
517
+ "json_flag",
518
+ required=False,
519
+ is_flag=True,
520
+ help="Output raw json",
521
+ )
522
+ @pass_ring
523
+ async def dings(ring: Ring, json_flag) -> None:
524
+ """Get dings information."""
525
+ if not json_flag:
526
+ echo(
527
+ "(Pretty format coming soon, if you want json consistently "
528
+ + "from this command provide the --json flag)"
529
+ )
530
+ echo(json.dumps(ring.dings_data, indent=2))
531
+
532
+
533
+ @cli.command()
534
+ @click.option(
535
+ "--json",
536
+ "json_flag",
537
+ required=False,
538
+ is_flag=True,
539
+ help="Output raw json",
540
+ )
541
+ @pass_ring
542
+ async def groups(ring: Ring, json_flag) -> None:
543
+ """Get group information."""
544
+ if not json_flag:
545
+ echo(
546
+ "(Pretty format coming soon, if you want json consistently "
547
+ + "from this command provide the --json flag)"
548
+ )
549
+ if not ring.groups_data:
550
+ echo("No ring device groups setup")
551
+ else:
552
+ for light_group in ring.groups().values():
553
+ await light_group.async_update()
554
+ echo(json.dumps(light_group._attrs, indent=2))
555
+ echo(json.dumps(light_group._health_attrs, indent=2))
556
+
557
+
558
+ @cli.command()
559
+ @click.option(
560
+ "--url",
561
+ required=True,
562
+ type=str,
563
+ help="Url to query, i.e. /clients_api/dings/active",
564
+ )
565
+ @pass_ring
566
+ async def raw_query(ring: Ring, url) -> None:
567
+ """Directly query a url and return json result."""
568
+ resp = await ring.async_query(url)
569
+ data = resp.json()
570
+ echo(json.dumps(data, indent=2))
571
+
572
+
573
+ @cli.command(name="history")
574
+ @click.option(
575
+ "--device-name",
576
+ "-dn",
577
+ required=False,
578
+ default=None,
579
+ help="Name of device, if ommited shows all devices",
580
+ )
581
+ @click.option(
582
+ "--limit",
583
+ required=False,
584
+ default=5,
585
+ help="Limit number of records to return",
586
+ )
587
+ @click.option(
588
+ "--kind",
589
+ required=False,
590
+ default=None,
591
+ type=click.Choice(["ding", "motion", "on_demand"], case_sensitive=False),
592
+ help="Get devices",
593
+ )
594
+ @click.option(
595
+ "--json",
596
+ "json_flag",
597
+ required=False,
598
+ is_flag=True,
599
+ help="Output raw json",
600
+ )
601
+ @pass_ring
602
+ @click.pass_context
603
+ async def history_command(ctx, ring: Ring, device_name, kind, limit, json_flag):
604
+ """Print raw json."""
605
+ if not json_flag:
606
+ echo(
607
+ "(Pretty format coming soon, if you want json consistently "
608
+ + "from this command provide the --json flag)"
609
+ )
610
+ device = ring.get_device_by_name(device_name)
611
+ if not device:
612
+ echo(
613
+ f"No device with name {device_name} found. "
614
+ + "List of found device names (kind) is:"
615
+ )
616
+ return await ctx.invoke(list_command)
617
+
618
+ history = await device.async_history(limit=limit, kind=kind, convert_timezone=False)
619
+ echo(json.dumps(history, indent=2))
620
+ return None
621
+
622
+
623
+ @cli.command()
624
+ @click.option(
625
+ "--count",
626
+ required=False,
627
+ default=False,
628
+ is_flag=True,
629
+ help="Count the number of videos on your Ring account",
630
+ )
631
+ @click.option(
632
+ "--download-all",
633
+ required=False,
634
+ default=False,
635
+ is_flag=True,
636
+ help="Download all videos on your Ring account",
637
+ )
638
+ @click.option(
639
+ "--download",
640
+ required=False,
641
+ default=False,
642
+ is_flag=True,
643
+ help="Download videos on your Ring account up to the max-count option",
644
+ )
645
+ @click.option(
646
+ "--max-count",
647
+ required=False,
648
+ default=300,
649
+ help="Maximum count of videos to count or download from your Ring account",
650
+ )
651
+ @click.option(
652
+ "--download-to",
653
+ required=False,
654
+ default="./",
655
+ help="Download location ending with a /",
656
+ )
657
+ @click.option(
658
+ "--device-name",
659
+ "-dn",
660
+ default=None,
661
+ required=False,
662
+ help="Name of the ring device, if omitted uses the first device returned",
663
+ )
664
+ @pass_ring
665
+ @click.pass_context
666
+ async def videos(
667
+ ctx, ring: Ring, count, download, download_all, max_count, download_to, device_name
668
+ ):
669
+ """Interact with ring videos."""
670
+ device = None
671
+ if device_name and not (device := ring.get_video_device_by_name(device_name)):
672
+ echo(
673
+ f"No device with name {device_name} found. "
674
+ + "List of found device names (kind) is:"
675
+ )
676
+ return await ctx.invoke(list_command)
677
+ if device and not device.has_capability("video"):
678
+ echo(f"Device {device.name} is not a video device")
679
+ return None
680
+ # return the first device is implemented to be consistent with previous cli version
681
+ if not device:
682
+ if video_devices := ring.video_devices():
683
+ device = video_devices[0]
684
+ else:
685
+ echo(
686
+ "No video devices found. "
687
+ + "List of found device names (with device kind) is:"
688
+ )
689
+ return await ctx.invoke(list_command)
690
+
691
+ if not device: # Make mypy happy
692
+ return None
693
+ if (
694
+ not count
695
+ and not download
696
+ and not download_all
697
+ and (last_recording_id := await device.async_get_last_recording_id())
698
+ and (url := await device.async_recording_url(last_recording_id))
699
+ ):
700
+ echo("Last recording url is: " + url)
701
+ return None
702
+
703
+ events = None
704
+ if download_all:
705
+ download = True
706
+ max_count = -1
707
+
708
+ async def _get_events(device, max_count):
709
+ limit = 100 if max_count == -1 else min(100, max_count)
710
+ events = []
711
+ history = await device.async_history(limit=limit)
712
+ while len(history) > 0:
713
+ events += history
714
+ if (len(events) >= max_count and max_count != -1) or len(history) < limit:
715
+ break
716
+ history = await device.async_history(
717
+ older_than=history[-1]["id"], limit=limit
718
+ )
719
+ return events
720
+
721
+ if count:
722
+ echo(
723
+ f"\tCounting videos linked on your Ring account for {device.name}.\n"
724
+ + "\tThis may take some time....\n"
725
+ )
726
+
727
+ events = await _get_events(device, max_count)
728
+
729
+ motion = len([m["kind"] for m in events if m["kind"] == "motion"])
730
+ ding = len([m["kind"] for m in events if m["kind"] == "ding"])
731
+ on_demand = len([m["kind"] for m in events if m["kind"] == "on_demand"])
732
+
733
+ echo(f"\tTotal videos: {len(events)}")
734
+ echo(f"\tDing triggered: {ding}")
735
+ echo(f"\tMotion triggered: {motion}")
736
+ echo(f"\tOn-Demand triggered: {on_demand}")
737
+
738
+ if download:
739
+ if events is None:
740
+ echo(
741
+ "\tGetting videos linked on your Ring account.\n"
742
+ "\tThis may take some time....\n"
743
+ )
744
+ events = await _get_events(device, max_count)
745
+
746
+ echo(
747
+ f"\tDownloading {len(events)} videos linked on your Ring account.\n"
748
+ "\tThis may take some time....\n"
749
+ )
750
+ for counter, event in enumerate(events):
751
+ filename = str(PurePath(download_to, _format_filename(device.name, event)))
752
+ echo(f"\t{counter}/{len(events)} Downloading {filename}")
753
+
754
+ await device.async_recording_download(
755
+ event["id"], filename=filename, override=False
756
+ )
757
+ return None
758
+ return None
759
+
760
+
761
+ @cli.group(invoke_without_command=True)
762
+ @pass_ring
763
+ @click.pass_context
764
+ @click.option(
765
+ "--device-name",
766
+ "-dn",
767
+ required=False,
768
+ default=None,
769
+ help="Name of the ring device",
770
+ )
771
+ async def in_home_chime(ctx, ring: Ring, device_name):
772
+ """View and manage the Doorbell in-home chime. To see the current in-home chime status of a device, only pass the device name."""
773
+ if "--help" in sys.argv:
774
+ return
775
+ device = _get_device(
776
+ ring,
777
+ ["authorized_doorbots", "doorbots"],
778
+ RingDoorBell,
779
+ device_name,
780
+ device_description="doorbell",
781
+ )
782
+
783
+ if ctx.invoked_subcommand is None:
784
+ echo("Name: %s" % device.name)
785
+ echo("ID: %s" % device.id)
786
+ echo("Type: %s" % device.existing_doorbell_type)
787
+ echo("Enabled: %s" % device.existing_doorbell_type_enabled)
788
+ echo("Duration: %s" % device.existing_doorbell_type_duration)
789
+ return None
790
+
791
+ ctx.obj = device
792
+
793
+
794
+ @in_home_chime.command(name="type")
795
+ @pass_doorbell
796
+ @click.pass_context
797
+ @click.argument(
798
+ "new_type",
799
+ type=click.Choice(list(DOORBELL_EXISTING_TYPE.values()), case_sensitive=False),
800
+ default=None,
801
+ required=False,
802
+ )
803
+ async def in_home_chime_type(ctx, device: RingDoorBell, new_type):
804
+ """Get/set the type of In-home chime."""
805
+ if new_type is None:
806
+ echo(device.existing_doorbell_type)
807
+ return
808
+
809
+ if device.family == "authorized_doorbots":
810
+ exit(
811
+ f"{device.name} is a shared device and you do not have permission to update this value"
812
+ )
813
+ new_type_int = next(k for k, v in DOORBELL_EXISTING_TYPE.items() if v == new_type)
814
+
815
+ await device.async_set_existing_doorbell_type(new_type_int)
816
+ echo(f"{device.name}'s in-home chime type has been set to {new_type}")
817
+
818
+
819
+ @in_home_chime.command()
820
+ @pass_doorbell
821
+ @click.pass_context
822
+ @click.argument("enable", type=click.BOOL, default=None, required=False)
823
+ async def enabled(ctx, device: RingDoorBell, enable: bool | None):
824
+ """Gets/sets the in-home chime enabled status.
825
+
826
+ ENABLE: 1/0, true/false, t/f, yes/no, y/n, and on/off
827
+ """
828
+ if enable is None:
829
+ echo(device.existing_doorbell_type_enabled)
830
+ return
831
+
832
+ if device.family == "authorized_doorbots":
833
+ exit(
834
+ f"{device.name} is a shared device and you do not have permission to update this value"
835
+ )
836
+ await device.async_set_existing_doorbell_type_enabled(enable)
837
+ echo(
838
+ f"{device.name}'s in-home chime has been {'enabled' if enable else 'disabled'}"
839
+ )
840
+
841
+
842
+ @in_home_chime.command()
843
+ @pass_doorbell
844
+ @click.pass_context
845
+ @click.argument("duration", type=click.IntRange(0, 100), default=None, required=False)
846
+ async def duration(ctx, device: RingDoorBell, duration: int | None):
847
+ """Gets/sets the in-home chime duration.
848
+
849
+ DURATION: Value between 0 and 100
850
+ """
851
+ if duration is None:
852
+ echo(device.existing_doorbell_type_duration)
853
+ return
854
+
855
+ if device.family == "authorized_doorbots":
856
+ exit(
857
+ f"{device.name} is a shared device and you do not have permission to update this value"
858
+ )
859
+ await device.async_set_existing_doorbell_type_duration(int(duration))
860
+ echo(f"{device.name}'s in-home chime duration has been set to {duration} seconds")
861
+
862
+
863
+ async def ainput(string: str):
864
+ loop = asyncio.get_event_loop()
865
+ await loop.run_in_executor(None, lambda s=string: sys.stdout.write(s + " ")) # type: ignore[misc]
866
+
867
+ return await loop.run_in_executor(None, sys.stdin.readline)
868
+
869
+
870
+ def get_now_str():
871
+ return str(datetime.utcnow())
872
+
873
+
874
+ class _event_handler: # pylint:disable=invalid-name
875
+ def __init__(self, ring: Ring) -> None:
876
+ self.ring = ring
877
+
878
+ def on_event(self, event: RingEvent) -> None:
879
+ msg = (
880
+ get_now_str()
881
+ + ": "
882
+ + str(event)
883
+ + " : Currently active count = "
884
+ + str(len(self.ring.push_dings_data))
885
+ )
886
+ echo(msg)
887
+
888
+
889
+ @cli.command
890
+ @click.option(
891
+ "--credentials-file",
892
+ required=False,
893
+ default=None,
894
+ help=(
895
+ "File to store push credentials, "
896
+ + "if not provided credentials will be recreated from scratch"
897
+ ),
898
+ )
899
+ @click.option(
900
+ "--store-credentials/--no-store-credentials",
901
+ default=True,
902
+ help="Whether or not to store the push credentials, default is false",
903
+ )
904
+ @click.option(
905
+ "--show-credentials",
906
+ default=False,
907
+ is_flag=True,
908
+ help="Whether or not to show the push credentials, default is false",
909
+ )
910
+ @pass_ring
911
+ @click.pass_context
912
+ async def listen(
913
+ ctx,
914
+ ring,
915
+ store_credentials,
916
+ credentials_file,
917
+ show_credentials,
918
+ ) -> None:
919
+ """Listen to push notification like the ones sent to your phone."""
920
+
921
+ from python_ring.listen import ( # pylint:disable=import-outside-toplevel
922
+ RingEventListener,
923
+ )
924
+
925
+ def credentials_updated_callback(credentials) -> None:
926
+ if store_credentials:
927
+ with open(credentials_file, "w", encoding="utf-8") as f:
928
+ json.dump(credentials, f)
929
+ else:
930
+ echo("New push credentials created:")
931
+ if show_credentials:
932
+ echo(credentials)
933
+
934
+ if not credentials_file:
935
+ credentials_file = gcm_cache_file
936
+ else:
937
+ credentials_file = Path(credentials_file)
938
+
939
+ credentials = None
940
+ if store_credentials and credentials_file.is_file():
941
+ # already registered, load previous credentials
942
+ with open(credentials_file, encoding="utf-8") as f:
943
+ credentials = json.load(f)
944
+
945
+ event_listener = RingEventListener(ring, credentials, credentials_updated_callback)
946
+ await event_listener.start()
947
+ event_listener.add_notification_callback(_event_handler(ring).on_event)
948
+
949
+ await ainput("Listening, press enter to cancel\n")
950
+
951
+ await event_listener.stop()
952
+
953
+
954
+ @cli.command
955
+ @click.option(
956
+ "--device-name",
957
+ required=False,
958
+ default=None,
959
+ help=("Name of the intercom if there are more than one."),
960
+ )
961
+ @pass_ring
962
+ @click.pass_context
963
+ async def open_door(ctx, ring: Ring, device_name: str | None) -> None:
964
+ """Open the door of a intercom device."""
965
+ device = _get_device(
966
+ ring,
967
+ ["intercoms", "other"],
968
+ RingOther,
969
+ device_name,
970
+ device_description="intercom",
971
+ )
972
+ await device.async_open_door()
973
+ echo(f"{device.name} opened")
974
+
975
+
976
+ if __name__ == "__main__":
977
+ cli() # pylint: disable=no-value-for-parameter