diff --git a/meshterm/context.py b/meshterm/context.py index d06cf7a..bd38ae8 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -33,6 +33,7 @@ from .core.remote_store import RemoteStore from .core.room_store import RoomStore from .core.selection import resolve_device from .core.settings_store import SettingsStore +from .core.sound_store import SoundStore from .core.watch_store import WatchStore from .persistence.logging import get_logger from .persistence.repository import Repository @@ -89,6 +90,9 @@ class AppContext: mute_store: The store for muted channel notifications. These are the channels whose new messages do not raise the unread badge (if the caller does not inject it, the default is ``/mutes.json``). + sound_store: The store for the sound setting of each conversation: when it plays a + sound, if it does not follow the default of its kind (if the caller does not + inject it, the default is ``/sounds.json``). region_store: The store for the regions that have a name, and for the send scope of each channel. MeshTerm resolves a scoped flood against it (if the caller does not inject it, the default is ``/regions.json``). @@ -152,6 +156,7 @@ class AppContext: watch_store: WatchStore | None = None courier_store: CourierStore | None = None mute_store: MuteStore | None = None + sound_store: SoundStore | None = None region_store: RegionStore | None = None channel_store: ChannelStore | None = None settings_store: SettingsStore | None = None @@ -233,6 +238,8 @@ class AppContext: self.courier_store = CourierStore(self.settings.config_dir / "courier.json") if self.mute_store is None: self.mute_store = MuteStore(self.settings.config_dir / "mutes.json") + if self.sound_store is None: + self.sound_store = SoundStore(self.settings.config_dir / "sounds.json") if self.region_store is None: self.region_store = RegionStore(self.settings.config_dir / "regions.json") if self.channel_store is None: diff --git a/meshterm/core/sound_store.py b/meshterm/core/sound_store.py new file mode 100644 index 0000000..b908abf --- /dev/null +++ b/meshterm/core/sound_store.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Storage for the sound setting of each conversation. + +Each conversation (a channel, a DM, or a room) has a **Sound** setting: ``off``, +``mentions``, or ``all`` (refer to +:data:`~meshterm.core.preferences.SOUND_WHEN_CHOICES`). A conversation that has no record +here follows the default of its kind, which is a preference (``channel_sound``, +``dm_sound``, ``room_sound``). Thus a new channel follows the default, and the user changes +the setting only where they want something else. + +The sound setting is not the mute of :class:`~meshterm.core.mute_store.MuteStore`. A mute +stops the unread count of a channel, and the setting here stops or starts its sound. The +user can mute the count of a busy public channel and still hear a mention in it. + +The key of a record is the key of the conversation +(:func:`~meshterm.core.models.conversation_key`): ``chan:`` for a channel, and +``dm:`` for a DM or a room. The unread count and the history use the same key. +It does not depend on a slot, so the setting stays with a channel that moves. + +The store is a small JSON file (``/sounds.json``), like the other choices of +the user. After the first read, it answers from memory, because the chat service reads it +for each received message. It writes each change immediately and atomically, from its +typed records (refer to :data:`ConversationSound.RETIRED`). +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import ClassVar + +from .atomicwrite import write_atomically + +#: The values of a sound setting that the store keeps. ``default`` is not a value here: it +#: is the absence of a record. +SOUND_WHEN = ("off", "mentions", "all") + + +@dataclass(slots=True) +class ConversationSound: + """The sound setting of one conversation. + + Attributes: + key: The key of the conversation (``chan:…`` or ``dm:…``). + when: When the conversation plays a sound: ``off``, ``mentions``, or ``all``. + """ + + key: str + when: str + + #: The field names that this record had once and does not have now. A field name that + #: leaves is never used again with a different meaning (refer to + #: :data:`meshterm.core.preferences.RETIRED` for the reason). + RETIRED: ClassVar[frozenset[str]] = frozenset() + + @classmethod + def read(cls, key: str, raw: object) -> ConversationSound | None: + """Make a record from its JSON form, or ``None`` if the form is not correct.""" + if not isinstance(raw, dict): + return None + when = raw.get("when") + if when not in SOUND_WHEN: + return None + return cls(key=key, when=when) + + def to_json(self) -> dict: + """The JSON form of the record, without its key.""" + return {"when": self.when} + + +class SoundStore: + """Reads and writes the sound setting of each conversation, from memory first.""" + + def __init__(self, path: Path) -> None: + """Open the store on the location of a JSON file. + + Args: + path: The path to the JSON file. The store makes the file at the first change. + """ + self._path = path + self._records: dict[str, ConversationSound] | None = None + + @property + def _state(self) -> dict[str, ConversationSound]: + """The records by conversation key, read from disk at the first access.""" + if self._records is None: + self._records = self._load() + return self._records + + def _load(self) -> dict[str, ConversationSound]: + """Read the records (empty for a missing or corrupt file).""" + try: + data = json.loads(self._path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + if not isinstance(data, dict): + return {} + records = {} + for key, raw in data.items(): + record = ConversationSound.read(str(key), raw) + if record is not None: + records[record.key] = record + return records + + def get(self, key: str) -> str | None: + """The sound setting of a conversation, or ``None`` when it follows the default.""" + record = self._state.get(key) + return record.when if record is not None else None + + def set(self, key: str, when: str | None) -> None: + """Change the sound setting of a conversation, and store only a real change. + + Args: + key: The key of the conversation. + when: ``off``, ``mentions``, or ``all``. ``None`` removes the record, so the + conversation follows the default of its kind again. + + Raises: + ValueError: If ``when`` is not one of the permitted values. + """ + if when is not None and when not in SOUND_WHEN: + raise ValueError(f"not a sound setting: {when!r}") + if self.get(key) == when: + return + if when is None: + self._state.pop(key, None) + else: + self._state[key] = ConversationSound(key=key, when=when) + data = {k: r.to_json() for k, r in sorted(self._state.items())} + write_atomically(self._path, json.dumps(data, indent=2)) diff --git a/meshterm/services/chat_service.py b/meshterm/services/chat_service.py index be5423a..0cbcc54 100644 --- a/meshterm/services/chat_service.py +++ b/meshterm/services/chat_service.py @@ -23,7 +23,7 @@ from collections import OrderedDict from collections.abc import Callable from typing import TYPE_CHECKING -from ..core.channels import channel_identity +from ..core.channels import MENTION, channel_identity from ..core.connection import Unsubscribe from ..core.events import EventKind, MeshEvent from ..core.models import ( @@ -36,6 +36,7 @@ from ..core.models import ( ) from ..core.regions import WILDCARD, normalize from .arrival_backfill import backfill_arrivals +from .sound import SoundEvent if TYPE_CHECKING: from ..context import AppContext @@ -380,8 +381,11 @@ class ChatService: channel_id = ( await self.channel_id_for(message.channel) if message.is_channel else None ) - notify = await self._notifies(message, channel_id) - self._store_inbound(run_id, message, channel_id, notify=notify) + listed = await self._is_listed(message, channel_id) + notify = listed and not self._is_muted(message, channel_id) + chat = self._store_inbound(run_id, message, channel_id, notify=notify) + if listed: + await self._play_sound(message, chat.key) except Exception as exc: # noqa: BLE001 - one bad message must not stop the worker self._ctx.log.debug("chat: failed to record message: %s", exc) finally: @@ -394,7 +398,7 @@ class ChatService: channel_id: str | None, *, notify: bool = True, - ) -> None: + ) -> ChatMessage: """Store an inbound message under a resolved identity, and increase its unread count. MeshTerm always stores the transcript. It does not increase the unread count for @@ -403,6 +407,9 @@ class ChatService: that the Chat picker cannot list (refer to :meth:`_notifies`). A message that does not notify is still written to history. Thus when the user opens its conversation later, the conversation shows all messages. + + Returns: + The stored message. """ chat = ChatMessage.from_message(message, channel_id=channel_id) self._session_count += 1 @@ -412,6 +419,7 @@ class ChatService: self._ctx.repo.record_chat_message(chat, run_id=run_id) except Exception as exc: # noqa: BLE001 - the storage must never break the subscription self._ctx.log.debug("chat: failed to record message: %s", exc) + return chat async def _notifies(self, message: Message, channel_id: str | None) -> bool: """Whether this message increases the unread badge in the header: the only badge rule. @@ -452,13 +460,88 @@ class ChatService: Returns: ``True`` to increase the unread count of the conversation. """ + if self._is_muted(message, channel_id): + return False + return await self._is_listed(message, channel_id) + + def _is_muted(self, message: Message, channel_id: str | None) -> bool: + """Whether the message is on a channel that the user muted (refer to MuteStore).""" + if not message.is_channel: + return False + store = getattr(self._ctx, "mute_store", None) + return store is not None and store.is_muted(channel_id) + + async def _is_listed(self, message: Message, channel_id: str | None) -> bool: + """Whether the Chat picker lists the conversation of the message (refer to _notifies). + + The unread badge and the sound both use this rule. A message that has no row to open + makes no sound, for the same reason that it does not increase the badge. + """ if message.is_channel: - store = getattr(self._ctx, "mute_store", None) - if store is not None and store.is_muted(channel_id): - return False return await self._is_listed_channel(channel_id) return await self._is_listed_contact(message.sender, post=message.is_post) + async def _play_sound(self, message: Message, key: str) -> None: + """Play the sound of a received message, if its conversation wants one. + + The rule (JP, 2026-11-20): + + * The open conversation makes no sound, the same as its unread count: the user + already sees the message. + * Each conversation has a sound setting (refer to + :class:`~meshterm.core.sound_store.SoundStore`), or follows the default of its + kind (the ``channel_sound``, ``dm_sound``, and ``room_sound`` preferences). + * ``off`` plays nothing. Otherwise a mention of our node plays the mention sound. + ``all`` plays the sound of the kind for each other message, and ``mentions`` + plays nothing for it. + + The channel mute is not part of this rule. It stops the unread count, not the sound. + A failure here must never stop the recording of messages, so it only goes to the log. + """ + if key == self._active: + return + sound = getattr(self._ctx, "sound", None) + if sound is None: + return + try: + event = await self._sound_event(message, key) + if event is not None: + sound.notify(event) + except Exception as exc: # noqa: BLE001 - a sound must never stop the recorder + self._ctx.log.debug("chat: sound failed: %s", exc) + + async def _sound_event(self, message: Message, key: str) -> SoundEvent | None: + """The sound event of a received message, or ``None`` for no sound.""" + if message.is_channel: + kind, event = "channel_sound", SoundEvent.CHANNEL_MESSAGE + elif message.is_post: + kind, event = "room_sound", SoundEvent.ROOM_POST + else: + kind, event = "dm_sound", SoundEvent.DIRECT_MESSAGE + store = getattr(self._ctx, "sound_store", None) + when = (store.get(key) if store is not None else None) or getattr( + self._ctx.preferences, kind + ) + if when == "off": + return None + if await self._mentions_us(message.text): + return SoundEvent.MENTION + return event if when == "all" else None + + async def _mentions_us(self, text: str | None) -> bool: + """Whether a message text mentions our node (``@[Name]`` with the name of our node).""" + if not text or "@[" not in text: + return False + devstate = getattr(self._ctx, "devstate", None) + if devstate is None: + return False + try: + info = await devstate.self_info() + except Exception: # noqa: BLE001 - with no name, nothing is a mention of us + return False + name = str(info.get("name") or "") + return bool(name) and any(m.group(1) == name for m in MENTION.finditer(text)) + async def _is_listed_channel(self, channel_id: str | None) -> bool: """Whether a channel identity is one of the configured channel slots of the device. diff --git a/tests/test_chat.py b/tests/test_chat.py index 96e957e..3020b74 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -11,6 +11,7 @@ import asyncio import logging import re from pathlib import Path +from types import SimpleNamespace import pytest from rich.cells import cell_len @@ -2779,6 +2780,142 @@ async def test_badge_still_respects_a_muted_channel(tmp_path: Path, repo: Reposi await device.disconnect() +# -- the sound of a received message ------------------------------------------------- + + +async def _sound_chat(repo: Repository, tmp_path: Path, **prefs: object): + """A chat service on the mock device with Public on slot 0, and a list of sound events.""" + from meshterm.core.sound_store import SoundStore + + device = MockDevice() + await device.connect() + device._channels[0] = { + "channel_idx": 0, + "channel_name": "Public", + "channel_secret": DEFAULT_PUBLIC_SECRET, + } + ctx = _GatedContext(device, repo) + ctx.preferences = Preferences(values=prefs) + ctx.sound_store = SoundStore(tmp_path / "sounds.json") + events: list = [] + ctx.sound = SimpleNamespace(notify=events.append) + chat = ChatService(ctx) + await chat.start() + return device, ctx, chat, events + + +def _public_key() -> str: + from meshterm.core.channels import channel_identity + + return f"chan:{channel_identity('Public', DEFAULT_PUBLIC_SECRET)}" + + +async def test_sound_a_dm_plays_by_default(tmp_path: Path, repo: Repository) -> None: + """A DM plays its sound by default (``dm_sound`` is ``all``).""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_channel_plays_only_for_a_mention_by_default( + tmp_path: Path, repo: Repository +) -> None: + """A channel plays nothing for a plain message, and the mention sound for a mention.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="Ann: hey all", channel=0, is_channel=True)) + assert events == [] + text = "Ann: hey @[MockCompanion]" + await _record(chat, ctx, Message(text=text, channel=0, is_channel=True)) + assert events == [SoundEvent.MENTION] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_the_setting_of_a_conversation_wins(tmp_path: Path, repo: Repository) -> None: + """The setting of one channel replaces the default of its kind: ``all``, then ``off``.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + ctx.sound_store.set(_public_key(), "all") + await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True)) + assert events == [SoundEvent.CHANNEL_MESSAGE] + ctx.sound_store.set(_public_key(), "off") + text = "Ann: @[MockCompanion] hi" + await _record(chat, ctx, Message(text=text, channel=0, is_channel=True)) + assert events == [SoundEvent.CHANNEL_MESSAGE] # off: not even a mention + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_the_default_of_a_kind_is_a_preference( + tmp_path: Path, repo: Repository +) -> None: + """``dm_sound = off`` silences each DM that has no setting of its own.""" + device, ctx, chat, events = await _sound_chat(repo, tmp_path, dm_sound="off") + try: + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + assert events == [] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_the_open_conversation_is_silent(tmp_path: Path, repo: Repository) -> None: + """The conversation on the screen plays nothing, the same as its unread count.""" + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + chat.set_active("dm:d4e5f6a7") + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + assert events == [] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_muted_channel_still_plays_a_mention( + tmp_path: Path, repo: Repository +) -> None: + """The mute stops the unread count, not the sound (JP, 2026-11-20).""" + from meshterm.core.channels import channel_identity + from meshterm.core.mute_store import MuteStore + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + ctx.mute_store = MuteStore(tmp_path / "mutes.json") + ctx.mute_store.set_muted(channel_identity("Public", DEFAULT_PUBLIC_SECRET), True) + text = "Ann: @[MockCompanion] look" + await _record(chat, ctx, Message(text=text, channel=0, is_channel=True)) + assert chat.unread(_public_key()) == 0 + assert events == [SoundEvent.MENTION] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_conversation_with_no_row_is_silent(tmp_path: Path, repo: Repository) -> None: + """A message that the Chat picker cannot list (a repeater reply) plays nothing.""" + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="> ok", sender="a1b2c3d4")) + assert events == [] + finally: + await chat.stop() + await device.disconnect() + + async def test_channel_slot_change_drops_the_cached_channel_list(repo: Repository) -> None: """If a slot resolves to a new identity, the cached channel list of the screens is invalid. diff --git a/tests/test_sound_store.py b/tests/test_sound_store.py new file mode 100644 index 0000000..fd02293 --- /dev/null +++ b/tests/test_sound_store.py @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The store of the sound setting of each conversation.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from meshterm.core.sound_store import SoundStore + + +def test_a_conversation_with_no_record_follows_the_default(tmp_path: Path) -> None: + """No record is ``None``: the conversation follows the default of its kind.""" + assert SoundStore(tmp_path / "sounds.json").get("chan:abc") is None + + +def test_a_setting_is_stored_and_read_again(tmp_path: Path) -> None: + """A setting goes to the file, and a new store reads it back.""" + path = tmp_path / "sounds.json" + SoundStore(path).set("dm:d4e5f6a7", "all") + assert SoundStore(path).get("dm:d4e5f6a7") == "all" + + +def test_none_removes_the_record(tmp_path: Path) -> None: + """``None`` removes the record, so the conversation follows the default again.""" + path = tmp_path / "sounds.json" + store = SoundStore(path) + store.set("chan:abc", "off") + store.set("chan:abc", None) + assert SoundStore(path).get("chan:abc") is None + assert json.loads(path.read_text(encoding="utf-8")) == {} + + +def test_a_bad_value_is_refused(tmp_path: Path) -> None: + """Only ``off``, ``mentions``, and ``all`` are settings.""" + with pytest.raises(ValueError): + SoundStore(tmp_path / "sounds.json").set("chan:abc", "loud") + + +def test_a_record_that_is_not_correct_is_not_read(tmp_path: Path) -> None: + """The store keeps only the records that it knows, and the next write removes the rest.""" + path = tmp_path / "sounds.json" + path.write_text( + json.dumps({"chan:a": {"when": "all"}, "chan:b": {"when": "loud"}, "chan:c": 3}), + encoding="utf-8", + ) + store = SoundStore(path) + assert store.get("chan:a") == "all" + assert store.get("chan:b") is None + store.set("chan:d", "off") + assert set(json.loads(path.read_text(encoding="utf-8"))) == {"chan:a", "chan:d"}