Repository: uilibs/uiprotect

Issue:
Play specific sound on chime
### Is your feature request related to a problem? Please describe.

There are multiple built-in sounds on the chime as well as the ability to upload your own. However this library only supports playing the default sound and the buzzer.

From the web UI it is possible to select any of the built-in or uploaded sounds and test them without changing the sounds used for a connected doorbell.

### Describe alternatives you've considered

None

### Additional context

_No response_

### Code of Conduct

- [X] I agree to follow this project's Code of Conduct

### Are you willing to resolve this issue by submitting a Pull Request?

- [ ] Yes, I have the time, and I know how to start.
- [ ] Yes, I have the time, but I don't know how to start. I would need guidance.
- [X] No, I don't have the time, although I believe I could do it if I had the time...
- [ ] No, I don't have the time and I wouldn't even know how to start.

Discussion:
coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>📥 Commits</summary>
> 
> Reviewing files that changed from the base of the PR and between f015a3a4b0bba44fd25580501197a1bb7b9b37e5 and 232d4c8563a8d5204c079ed2db35fea7bdbb9759.
> 
> </details>
> 
> <details>
> <summary>📒 Files selected for processing (7)</summary>
> 
> * `src/uiprotect/api.py` (1 hunks)
> * `src/uiprotect/data/bootstrap.py` (2 hunks)
> * `src/uiprotect/data/convert.py` (2 hunks)
> * `src/uiprotect/data/devices.py` (1 hunks)
> * `src/uiprotect/data/types.py` (1 hunks)
> * `tests/sample_data/sample_bootstrap.json` (1 hunks)
> * `tests/test_api.py` (1 hunks)
> 
> </details>
> 
> ```ascii
>  ________________________________________________________________
> < Pop quiz, hotshot. There's a bug in your code. What do you do? >
>  ----------------------------------------------------------------
>   \
>    \   (\__/)
>        (•ㅅ•)
>        / 　 づ
> ```

<!-- end of auto-generated comment: review in progress by coderabbit.ai -->

<!-- usage_tips_start -->

> [!TIP]
> <details>
> <summary>You can disable poems in the walkthrough.</summary>
> 
> Disable the `reviews.poem` setting in your project's settings in CodeRabbit to disable the poems in the walkthrough.
> 
> </details>

<!-- usage_tips_end -->
<!-- tips_start -->

---

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai generate unit testing code for this file.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and generate unit testing code.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR. ([Beta](https://docs.coderabbit.ai/early-access#beta))
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs) Report
All modified and coverable lines are covered by tests :white_check_mark:

| [Files with missing lines](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs) | Coverage Δ | |
|---|---|---|
| [src/uiprotect/api.py](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?src=pr&el=tree&filepath=src%2Fuiprotect%2Fapi.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs#diff-c3JjL3VpcHJvdGVjdC9hcGkucHk=) | `56.82% <100.00%> (+0.28%)` | :arrow_up: |
| [src/uiprotect/data/bootstrap.py](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?src=pr&el=tree&filepath=src%2Fuiprotect%2Fdata%2Fbootstrap.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs#diff-c3JjL3VpcHJvdGVjdC9kYXRhL2Jvb3RzdHJhcC5weQ==) | `68.93% <100.00%> (+0.09%)` | :arrow_up: |
| [src/uiprotect/data/convert.py](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?src=pr&el=tree&filepath=src%2Fuiprotect%2Fdata%2Fconvert.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs#diff-c3JjL3VpcHJvdGVjdC9kYXRhL2NvbnZlcnQucHk=) | `88.88% <ø> (ø)` | |
| [src/uiprotect/data/devices.py](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?src=pr&el=tree&filepath=src%2Fuiprotect%2Fdata%2Fdevices.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs#diff-c3JjL3VpcHJvdGVjdC9kYXRhL2RldmljZXMucHk=) | `86.32% <100.00%> (+0.05%)` | :arrow_up: |
| [src/uiprotect/data/types.py](https://app.codecov.io/gh/uilibs/uiprotect/pull/346?src=pr&el=tree&filepath=src%2Fuiprotect%2Fdata%2Ftypes.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=uilibs#diff-c3JjL3VpcHJvdGVjdC9kYXRhL3R5cGVzLnB5) | `99.80% <100.00%> (+<0.01%)` | :arrow_up: |


Patch:
diff --git a/src/uiprotect/api.py b/src/uiprotect/api.py
index 07f8156..a63fb19 100644
--- a/src/uiprotect/api.py
+++ b/src/uiprotect/api.py
@@ -1806,10 +1806,12 @@ class ProtectApiClient(BaseApiClient):
         *,
         volume: int | None = None,
         repeat_times: int | None = None,
+        ringtone_id: str | None = None,
+        track_no: int | None = None,
     ) -> None:
         """Plays chime tones on a chime"""
         data: dict[str, Any] | None = None
-        if volume or repeat_times:
+        if volume or repeat_times or ringtone_id or track_no:
             chime = self.bootstrap.chimes.get(device_id)
             if chime is None:
                 raise BadRequest("Invalid chime ID %s", device_id)
@@ -1817,8 +1819,11 @@ class ProtectApiClient(BaseApiClient):
             data = {
                 "volume": volume or chime.volume,
                 "repeatTimes": repeat_times or chime.repeat_times,
-                "trackNo": chime.track_no,
+                "trackNo": track_no or chime.track_no,
             }
+            if ringtone_id:
+                data["ringtoneId"] = ringtone_id
+                data.pop("trackNo", None)
 
         await self.api_request(
             f"chimes/{device_id}/play-speaker",
diff --git a/src/uiprotect/data/bootstrap.py b/src/uiprotect/data/bootstrap.py
index ea5c3e1..4e59a77 100644
--- a/src/uiprotect/data/bootstrap.py
+++ b/src/uiprotect/data/bootstrap.py
@@ -30,6 +30,7 @@ from .devices import (
     Doorlock,
     Light,
     ProtectAdoptableDeviceModel,
+    Ringtone,
     Sensor,
     Viewer,
 )
@@ -183,6 +184,7 @@ class Bootstrap(ProtectBaseObject):
     doorlocks: dict[str, Doorlock]
     chimes: dict[str, Chime]
     aiports: dict[str, AiPort]
+    ringtones: list[Ringtone]
     last_update_id: str
 
     # TODO:
diff --git a/src/uiprotect/data/devices.py b/src/uiprotect/data/devices.py
index 31f98c7..2eab959 100644
--- a/src/uiprotect/data/devices.py
+++ b/src/uiprotect/data/devices.py
@@ -3388,3 +3388,12 @@ class Chime(ProtectAdoptableDeviceModel):
 
 class AiPort(Camera):
     paired_cameras: list[str]
+
+
+class Ringtone(ProtectBaseObject):
+    id: str
+    name: str
+    size: int
+    is_default: bool
+    nvr_mac: str
+    model_key: str
diff --git a/src/uiprotect/data/types.py b/src/uiprotect/data/types.py
index d24be37..0e8a805 100644
--- a/src/uiprotect/data/types.py
+++ b/src/uiprotect/data/types.py
@@ -128,6 +128,7 @@ class ModelType(str, UnknownValuesEnumMixin, enum.Enum):
     DEVICE_GROUP = "deviceGroup"
     RECORDING_SCHEDULE = "recordingSchedule"
     ULP_USER = "ulpUser"
+    RINGTONE = "ringtone"
     KEYRING = "keyring"
     UNKNOWN = "unknown"
 


Test patch:
diff --git a/tests/sample_data/sample_bootstrap.json b/tests/sample_data/sample_bootstrap.json
index 5bc7a68..6b391ac 100644
--- a/tests/sample_data/sample_bootstrap.json
+++ b/tests/sample_data/sample_bootstrap.json
@@ -7276,6 +7276,24 @@
             "modelKey": "chime"
         }
     ],
+    "ringtones": [
+        {
+            "id": "66a14fa502d44203e40003eb",
+            "name": "Default",
+            "size": 208,
+            "isDefault": true,
+            "nvrMac": "4B8290F6D7A3",
+            "modelKey": "ringtone"
+        },
+        {
+            "id": "66a14fa502da4203e40003ec",
+            "name": "custometest",
+            "size": 180,
+            "isDefault": false,
+            "nvrMac": "4B8290F6D7A3",
+            "modelKey": "ringtone"
+        }
+    ],
     "aiports": [
         {
             "isDeleting": false,
diff --git a/tests/test_api.py b/tests/test_api.py
index 4c867fb..f872f87 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -969,3 +969,99 @@ async def test_get_aiports(protect_client: ProtectApiClient, aiports):
     objs = [create_from_unifi_dict(d) for d in aiports]
 
     assert_equal_dump(objs, await protect_client.get_aiports())
+
+
+@pytest.mark.asyncio()
+async def test_play_speaker(protect_client: ProtectApiClient):
+    """Test play_speaker with default parameters."""
+    device_id = "cf1a330397c08f919d02bd7c"
+    protect_client.api_request = AsyncMock()
+
+    await protect_client.play_speaker(device_id)
+
+    protect_client.api_request.assert_called_with(
+        f"chimes/{device_id}/play-speaker",
+        method="post",
+        json=None,
+    )
+
+
+@pytest.mark.asyncio()
+async def test_play_speaker_with_volume(protect_client: ProtectApiClient):
+    """Test play_speaker with volume parameter."""
+    device_id = "cf1a330397c08f919d02bd7c"
+    volume = 5
+    chime = protect_client.bootstrap.chimes[device_id]
+    protect_client.api_request = AsyncMock()
+
+    await protect_client.play_speaker(device_id, volume=volume)
+
+    protect_client.api_request.assert_called_with(
+        f"chimes/{device_id}/play-speaker",
+        method="post",
+        json={
+            "volume": volume,
+            "repeatTimes": chime.repeat_times,
+            "trackNo": chime.track_no,
+        },
+    )
+
+
+@pytest.mark.asyncio()
+async def test_play_speaker_with_ringtone_id(protect_client: ProtectApiClient):
+    """Test play_speaker with ringtone_id parameter."""
+    device_id = "cf1a330397c08f919d02bd7c"
+    ringtone_id = "ringtone_1"
+    chime = protect_client.bootstrap.chimes[device_id]
+    protect_client.api_request = AsyncMock()
+
+    await protect_client.play_speaker(device_id, ringtone_id=ringtone_id)
+
+    protect_client.api_request.assert_called_with(
+        f"chimes/{device_id}/play-speaker",
+        method="post",
+        json={
+            "volume": chime.volume,
+            "repeatTimes": chime.repeat_times,
+            "ringtoneId": ringtone_id,
+        },
+    )
+
+
+@pytest.mark.asyncio()
+async def test_play_speaker_invalid_chime_id(protect_client: ProtectApiClient):
+    """Test play_speaker with invalid chime ID."""
+    device_id = "invalid_id"
+    protect_client.api_request = AsyncMock()
+
+    with pytest.raises(BadRequest):
+        await protect_client.play_speaker(device_id, volume=5)
+
+
+@pytest.mark.asyncio()
+async def test_play_speaker_with_all_parameters(protect_client: ProtectApiClient):
+    """Test play_speaker with all parameters."""
+    device_id = "cf1a330397c08f919d02bd7c"
+    volume = 5
+    repeat_times = 3
+    ringtone_id = "ringtone_1"
+    track_no = 2
+    protect_client.api_request = AsyncMock()
+
+    await protect_client.play_speaker(
+        device_id,
+        volume=volume,
+        repeat_times=repeat_times,
+        ringtone_id=ringtone_id,
+        track_no=track_no,
+    )
+
+    protect_client.api_request.assert_called_with(
+        f"chimes/{device_id}/play-speaker",
+        method="post",
+        json={
+            "volume": volume,
+            "repeatTimes": repeat_times,
+            "ringtoneId": ringtone_id,
+        },
+    )