Each sound event has its own switch; the per-conversation sound settings are gone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
da2e5d3044
commit
d6a5bed974
15 files changed
+212
-683
No files matched your search
+2
-4
@@ -23,10 +23,8 @@ can change how things behave. It does not only add new things.
|
||||
- **MeshTerm plays sounds for the messages that you want to know about.** A DM, a mention
|
||||
of your node, a channel message, a room post, and a low battery each have their own
|
||||
sound, from Android's set (the Android Open Source Project, under the same licence as
|
||||
MeshTerm). Channels follow one preference, *Channel sound* (mentions only by default), and
|
||||
a muted channel is silent. Each DM and room has a *Sound* row: never, mentions only, every
|
||||
message, or the default for its kind (every message for a DM, mentions only for a room).
|
||||
*Mentions always* (on by default) plays each mention of your node, also on a muted channel.
|
||||
MeshTerm). Each event has its own switch, all on except the packet tick. A muted channel
|
||||
is silent, also for a mention, and so is the conversation that is open on the screen.
|
||||
Ctrl+S mutes or unmutes the sounds from any screen, and the header shows 🔊 or 🔇. The
|
||||
new *Sound* group of preferences has the theme (Android, terminal bell, or no sound), a
|
||||
volume slider of ten steps that plays each step, a short tick for each packet heard (off
|
||||
|
||||
@@ -563,7 +563,7 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow
|
||||
🔒 lock (a locked contact, a private channel) · 🔓 unlock · 🗑 clear/delete · ✎ compose/edit ·
|
||||
⚙ parameter · `#` count · ▶ run · ⚡ explore/probe · ★ best/winner · ⭐ watch ·
|
||||
📤 send now · 📨 courier/queue · 💬 chat · 🔔 notify · 🔕 mute (notifications off) ·
|
||||
🔊 sound on / a conversation's Sound row · 🔇 sounds muted (header, menu row) ·
|
||||
🔊 sounds on · 🔇 sounds muted (header, menu row) ·
|
||||
📱 QR · 🔗 link · ↻ re-read · ↕ reorder · ⇄ reverse (flip a path's direction) ·
|
||||
🔖 region/scope · 📌 rooms · 🏆 trophy case/record · ⌨ command line · 📖 read/about · 💰 support/donate ·
|
||||
🎨 pixel image (an MCOimg picture in a message) · 🚪 quit. Packet-class icons (feed/viewer
|
||||
|
||||
+14
-21
@@ -79,30 +79,23 @@ only describe it. The written pages are at the end.
|
||||
|
||||
## Sounds
|
||||
|
||||
MeshTerm plays a sound when something arrives that you want to know about now:
|
||||
MeshTerm plays a sound when something arrives that you want to know about now. Each event
|
||||
has its own sound, and its own switch on the Preferences page:
|
||||
|
||||
| Event | When it plays |
|
||||
| --- | --- |
|
||||
| Direct message | A DM arrives |
|
||||
| Mention | A message in any conversation mentions your node (`@[Your name]`) |
|
||||
| Channel message | A message arrives on a channel that is not muted, when **Channel sound** is **every message** |
|
||||
| Room post | A post arrives in a room whose sound is **every message** |
|
||||
| Battery low | The battery goes below 25% (the **Battery low** preference). It plays one time, and again only after the battery is 5 points higher or charges |
|
||||
| Packet tick | A very short tick for each packet heard that plays no other sound. It is off until you turn on **Packet tick**, and it plays at most four times each second |
|
||||
| Event | When it plays | Default |
|
||||
| --- | --- | --- |
|
||||
| Direct message | A DM arrives | on |
|
||||
| Mention | A message mentions your node (`@[Your name]`). With this switch off, the message plays the sound of its kind | on |
|
||||
| Channel message | A message arrives on a channel | on |
|
||||
| Room post | A room sends a new post | on |
|
||||
| Battery low | The battery goes below the **Low level** (25%). It plays one time, and again only after the battery is 5 points higher or charges | on |
|
||||
| Packet tick | A very short tick for each packet heard that plays no other sound, at most four times each second | off |
|
||||
|
||||
The conversation that is open on the screen makes no sound, because you already see it.
|
||||
Two things are always silent:
|
||||
|
||||
All channels follow one preference, **Channel sound**: **never**, **mentions only** (the
|
||||
default), or **every message**. A channel that you muted (🔕) is silent, because the mute
|
||||
turns off all of its notifications.
|
||||
|
||||
Each DM and room has a **Sound** row: on the node page of the contact, and on the room page.
|
||||
Select **never**, **mentions only**, **every message**, or **Default**. Default follows the
|
||||
preference for that kind of conversation: every message for a DM, and mentions only for a
|
||||
room.
|
||||
|
||||
**Mentions always** (on by default) plays the mention sound for each mention of your node,
|
||||
also on a muted channel and in a DM or a room set to **never**.
|
||||
- The conversation that is open on the screen, because you already see it.
|
||||
- A channel that you muted (🔕), also for a mention. The mute turns off all of the
|
||||
notifications of the channel.
|
||||
|
||||
**Ctrl+S** mutes or unmutes the sounds from any screen. The header shows 🔊 while the
|
||||
sounds play and 🔇 while they are muted. The **Sound** row above Quit in the main menu
|
||||
|
||||
@@ -33,7 +33,6 @@ 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
|
||||
@@ -90,9 +89,6 @@ 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 ``<config_dir>/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 ``<config_dir>/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 ``<config_dir>/regions.json``).
|
||||
@@ -156,7 +152,6 @@ 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
|
||||
@@ -238,8 +233,6 @@ 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:
|
||||
|
||||
@@ -180,14 +180,6 @@ _SOUND_THEME_CHOICES: dict[str, str] = {
|
||||
#: player failed.
|
||||
_FLASH_CHOICES: dict[str, str] = {"off": "off", "on": "on", "silent": "when silent"}
|
||||
|
||||
#: When a conversation plays its sound. A mention of our node always plays the mention
|
||||
#: sound, unless the conversation is ``off``.
|
||||
SOUND_WHEN_CHOICES: dict[str, str] = {
|
||||
"off": "never",
|
||||
"mentions": "mentions only",
|
||||
"all": "every message",
|
||||
}
|
||||
|
||||
#: The sources of the place of a node (refer to :mod:`meshterm.services.places`). With
|
||||
#: ``tiles_nominatim``, the map tiles give the first answer at once, and Nominatim corrects it
|
||||
#: later, when MeshTerm is online, because only Nominatim knows the boundaries of a place.
|
||||
@@ -561,72 +553,67 @@ PREFERENCES: tuple[PrefSpec, ...] = (
|
||||
default="silent",
|
||||
choices=_FLASH_CHOICES,
|
||||
),
|
||||
# One switch for each sound event (JP, 2026-11-21: "These events should have on/off
|
||||
# setting. All default to on, except packet tick"). A muted channel stays silent, and
|
||||
# the conversation on the screen makes no sound.
|
||||
PrefSpec(
|
||||
key="dm_sound",
|
||||
label="DM sound",
|
||||
help="Unless set per DM",
|
||||
question="When a DM plays a sound, unless the DM has its own setting",
|
||||
group="Sound",
|
||||
value_type="enum",
|
||||
default="all",
|
||||
choices=SOUND_WHEN_CHOICES,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="channel_sound",
|
||||
label="Channel sound",
|
||||
help="For channels not muted",
|
||||
question="When a channel plays a sound. A muted channel plays none",
|
||||
group="Sound",
|
||||
value_type="enum",
|
||||
# Mentions: a public channel can carry many messages each hour.
|
||||
default="mentions",
|
||||
choices=SOUND_WHEN_CHOICES,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="mention_sound_always",
|
||||
label="Mentions always",
|
||||
help="Even if muted or never",
|
||||
question=(
|
||||
"Play the mention sound for each mention of your node, also on a muted channel"
|
||||
" and in a conversation set to never"
|
||||
),
|
||||
key="sound_dm",
|
||||
label="Direct message",
|
||||
help="When a DM arrives",
|
||||
question="Play a sound when a direct message arrives",
|
||||
group="Sound",
|
||||
value_type="bool",
|
||||
# On: a mention is the message that the user most wants to hear (JP, 2026-11-21:
|
||||
# "a global always play sound for mentions"). The ^S mute still silences it.
|
||||
default=True,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="room_sound",
|
||||
label="Room sound",
|
||||
help="Unless set per room",
|
||||
question="When a room plays a sound, unless the room has its own setting",
|
||||
key="sound_mention",
|
||||
label="Mention",
|
||||
help="When a message names you",
|
||||
question=(
|
||||
"Play the mention sound when a message mentions your node. Off: the message"
|
||||
" plays the sound of its kind"
|
||||
),
|
||||
group="Sound",
|
||||
value_type="enum",
|
||||
default="mentions",
|
||||
choices=SOUND_WHEN_CHOICES,
|
||||
value_type="bool",
|
||||
default=True,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="packet_tick",
|
||||
label="Packet tick",
|
||||
help="A tick for other packets",
|
||||
question="A short tick for each packet heard that plays no other sound",
|
||||
key="sound_channel",
|
||||
label="Channel message",
|
||||
help="Not on a muted channel",
|
||||
question="Play a sound when a message arrives on a channel that is not muted",
|
||||
group="Sound",
|
||||
value_type="bool",
|
||||
# Off: a busy mesh can send many packets each minute. The service plays at most one
|
||||
# tick each 250 ms (JP, 2026-11-20).
|
||||
default=False,
|
||||
default=True,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="sound_room",
|
||||
label="Room post",
|
||||
help="When a room sends a post",
|
||||
question="Play a sound when a room sends a new post",
|
||||
group="Sound",
|
||||
value_type="bool",
|
||||
default=True,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="sound_battery",
|
||||
label="Battery low",
|
||||
help="When the battery goes low",
|
||||
question="Play a sound when the battery goes below the low level",
|
||||
group="Sound",
|
||||
value_type="bool",
|
||||
default=True,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="battery_low_pct",
|
||||
label="Battery low",
|
||||
help="Plays the battery sound",
|
||||
question="Play the battery sound when the battery goes below this level",
|
||||
label="Low level",
|
||||
help="Where the battery is low",
|
||||
question="The battery level below which the battery sound plays",
|
||||
group="Sound",
|
||||
value_type="int",
|
||||
# 25: the level where the gauge of the header changes to its low band (batt.low).
|
||||
@@ -636,6 +623,18 @@ PREFERENCES: tuple[PrefSpec, ...] = (
|
||||
unit="%",
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
PrefSpec(
|
||||
key="packet_tick",
|
||||
label="Packet tick",
|
||||
help="A tick for other packets",
|
||||
question="Play a short tick for each packet heard that plays no other sound",
|
||||
group="Sound",
|
||||
value_type="bool",
|
||||
# Off: a busy mesh can send many packets each minute. The service plays at most one
|
||||
# tick each 250 ms (JP, 2026-11-20).
|
||||
default=False,
|
||||
platforms=_SOUND_PLATFORMS,
|
||||
),
|
||||
# --- History kept ------------------------------------------------------------
|
||||
PrefSpec(
|
||||
key="history_days",
|
||||
@@ -863,6 +862,12 @@ RETIRED: frozenset[str] = frozenset(
|
||||
# replaced, and a volume in percent that a slider of ten steps replaced.
|
||||
"sounds",
|
||||
"sound_volume_pct",
|
||||
# The sound of each kind of conversation (never, mentions only, or every message)
|
||||
# and the mention override, replaced on 2026-11-21 by one switch for each event.
|
||||
"dm_sound",
|
||||
"channel_sound",
|
||||
"room_sound",
|
||||
"mention_sound_always",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# 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:<identity>`` for a channel, and
|
||||
``dm:<key prefix>`` 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 (``<config_dir>/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))
|
||||
@@ -482,64 +482,41 @@ class ChatService:
|
||||
return await self._is_listed_contact(message.sender, post=message.is_post)
|
||||
|
||||
async def _play_sound(self, message: Message, key: str, *, muted: bool = False) -> None:
|
||||
"""Play the sound of a received message, if its conversation wants one.
|
||||
"""Play the sound of a received message.
|
||||
|
||||
The rule (JP, 2026-11-21):
|
||||
|
||||
* The open conversation makes no sound, the same as its unread count: the user
|
||||
already sees the message.
|
||||
* With ``mention_sound_always`` on (the default), a mention of our node always plays
|
||||
the mention sound, also on a muted channel and in a conversation set to ``off``.
|
||||
* A muted channel (``muted``, refer to MuteStore) plays nothing else. A mute turns
|
||||
off the notifications of the channel, and a sound is one.
|
||||
* A channel follows the ``channel_sound`` preference. Channels have no setting of
|
||||
their own. A DM and a room have their own setting (refer to
|
||||
:class:`~meshterm.core.sound_store.SoundStore`), or follow ``dm_sound`` and
|
||||
``room_sound``.
|
||||
* ``off`` plays nothing. Otherwise a mention plays the mention sound. ``all`` plays
|
||||
the sound of the kind for each other message, and ``mentions`` plays nothing for
|
||||
it.
|
||||
* A muted channel (``muted``, refer to MuteStore) makes no sound, also for a
|
||||
mention. A mute turns off the notifications of the channel, and a sound is one.
|
||||
* A mention of our node plays the mention sound. Other messages play the sound of
|
||||
their kind: a DM, a channel message, or a room post.
|
||||
* Each event has its own switch (refer to
|
||||
:data:`~meshterm.services.sound.EVENT_PREFERENCE`). When the mention switch is
|
||||
off, a mention plays the sound of its kind instead. When the switch of the kind is
|
||||
off too, nothing plays.
|
||||
|
||||
A failure here must never stop the recording of messages, so it only goes to the log.
|
||||
"""
|
||||
if key == self._active:
|
||||
if key == self._active or muted:
|
||||
return
|
||||
sound = getattr(self._ctx, "sound", None)
|
||||
if sound is None:
|
||||
return
|
||||
try:
|
||||
event = await self._sound_event(message, key, muted=muted)
|
||||
if event is not None:
|
||||
sound.notify(event)
|
||||
if message.is_channel:
|
||||
event = SoundEvent.CHANNEL_MESSAGE
|
||||
elif message.is_post:
|
||||
event = SoundEvent.ROOM_POST
|
||||
else:
|
||||
event = SoundEvent.DIRECT_MESSAGE
|
||||
if sound.event_on(SoundEvent.MENTION) and await self._mentions_us(message.text):
|
||||
event = SoundEvent.MENTION
|
||||
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, *, muted: bool = False
|
||||
) -> SoundEvent | None:
|
||||
"""The sound event of a received message, or ``None`` for no sound."""
|
||||
prefs = self._ctx.preferences
|
||||
mention = await self._mentions_us(message.text)
|
||||
if mention and prefs.mention_sound_always:
|
||||
return SoundEvent.MENTION
|
||||
if message.is_channel:
|
||||
if muted:
|
||||
return None
|
||||
when, event = prefs.channel_sound, SoundEvent.CHANNEL_MESSAGE
|
||||
else:
|
||||
kind, event = (
|
||||
("room_sound", SoundEvent.ROOM_POST)
|
||||
if message.is_post
|
||||
else ("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(prefs, kind)
|
||||
if when == "off":
|
||||
return None
|
||||
if mention:
|
||||
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:
|
||||
|
||||
@@ -95,6 +95,17 @@ TICK_DELAY_S = 0.15
|
||||
#: around the threshold plays the sound at each poll.
|
||||
BATTERY_REARM_PCT = 5
|
||||
|
||||
#: The preference that turns each event on or off (JP, 2026-11-21). All are on by default,
|
||||
#: except the packet tick.
|
||||
EVENT_PREFERENCE: dict[SoundEvent, str] = {
|
||||
SoundEvent.DIRECT_MESSAGE: "sound_dm",
|
||||
SoundEvent.MENTION: "sound_mention",
|
||||
SoundEvent.CHANNEL_MESSAGE: "sound_channel",
|
||||
SoundEvent.ROOM_POST: "sound_room",
|
||||
SoundEvent.BATTERY_LOW: "sound_battery",
|
||||
SoundEvent.PACKET_TICK: "packet_tick",
|
||||
}
|
||||
|
||||
#: The minimum seconds between the start of a sound and a packet tick. It limits the tick
|
||||
#: to four each second on a busy mesh, and a tick does not play over the start of another
|
||||
#: sound (JP, 2026-11-20).
|
||||
@@ -311,6 +322,10 @@ class SoundService:
|
||||
"""Whether the theme makes a sound (``android`` or ``bell``, not ``none``)."""
|
||||
return self._prefs.sound_theme != "none"
|
||||
|
||||
def event_on(self, event: SoundEvent) -> bool:
|
||||
"""Whether the preference of an event turns it on (refer to EVENT_PREFERENCE)."""
|
||||
return bool(self._prefs.get(EVENT_PREFERENCE[event]))
|
||||
|
||||
def toggle(self) -> bool:
|
||||
"""Mute or unmute the sounds (the ^S key), and save the preference.
|
||||
|
||||
@@ -328,18 +343,19 @@ class SoundService:
|
||||
def notify(self, event: SoundEvent) -> bool:
|
||||
"""Play the sound of an event, and flash the title bar if the preference says so.
|
||||
|
||||
An event that its preference turns off does nothing: no sound, and no flash.
|
||||
|
||||
Args:
|
||||
event: The event.
|
||||
|
||||
Returns:
|
||||
``True`` if a sound started (a file or the bell).
|
||||
"""
|
||||
if not self.event_on(event):
|
||||
return False
|
||||
tick = event is SoundEvent.PACKET_TICK
|
||||
if tick:
|
||||
if not self._prefs.packet_tick:
|
||||
return False
|
||||
if self._clock() - self._last_sound < TICK_GAP_S:
|
||||
return False
|
||||
if tick and self._clock() - self._last_sound < TICK_GAP_S:
|
||||
return False
|
||||
audible = self.enabled and self._emit(event)
|
||||
if not tick:
|
||||
mode = self._prefs.notify_flash
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The *Sound…* row of a conversation, and the picker that it opens.
|
||||
|
||||
A DM and a room each have a sound setting (refer to
|
||||
:class:`~meshterm.core.sound_store.SoundStore`): ``off``, ``mentions``, ``all``, or the
|
||||
default of its kind (a preference). Two pages show the row: the node page of a contact,
|
||||
and the page of a room. They both build it here, so that the words and the picker are the
|
||||
same on each page.
|
||||
|
||||
A channel has no sound setting of its own (JP, 2026-11-21). All channels follow the
|
||||
``channel_sound`` preference, and the mute of a channel makes it silent.
|
||||
|
||||
The row is only on a platform that can play a sound. The PicoCalc has no sound, so a
|
||||
setting there would change nothing that the user can hear.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
from ..core.preferences import SOUND_WHEN_CHOICES
|
||||
from .menus import marked_label
|
||||
from .tui import Choice
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
|
||||
#: The icon of the row.
|
||||
SOUND_ICON = "🔊"
|
||||
|
||||
#: The value with which the row resolves.
|
||||
SOUND_ROW = "sound"
|
||||
|
||||
#: The value of the picker for "follow the default of the kind". The store keeps no record
|
||||
#: for it.
|
||||
_DEFAULT = "default"
|
||||
|
||||
#: The preference that holds the default of each kind of conversation.
|
||||
KIND_PREFERENCE = {"dm": "dm_sound", "room": "room_sound"}
|
||||
|
||||
|
||||
def offered(ctx: AppContext) -> bool:
|
||||
"""Whether the pages show the row: the platform can play a sound."""
|
||||
sound = getattr(ctx, "sound", None)
|
||||
return sound is not None and sound.available
|
||||
|
||||
|
||||
def _default_when(ctx: AppContext, kind: str) -> str:
|
||||
"""The default sound setting of a kind of conversation, from its preference."""
|
||||
return str(ctx.preferences.get(KIND_PREFERENCE[kind]))
|
||||
|
||||
|
||||
def describe(ctx: AppContext, key: str, kind: str) -> str:
|
||||
"""The description of the row: what the conversation plays now.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
key: The key of the conversation (``chan:…`` or ``dm:…``).
|
||||
kind: ``dm`` or ``room``.
|
||||
|
||||
Returns:
|
||||
A short sentence, for example ``Default: mentions only``.
|
||||
"""
|
||||
own = ctx.sound_store.get(key)
|
||||
when = own or _default_when(ctx, kind)
|
||||
text = {
|
||||
"off": "No sound",
|
||||
"mentions": "A sound for mentions only",
|
||||
"all": "A sound for each message",
|
||||
}[when]
|
||||
return text if own else f"Default: {SOUND_WHEN_CHOICES[when]}"
|
||||
|
||||
|
||||
def sound_row(ctx: AppContext, key: str, kind: str, lane: int) -> tuple[Text, str, str]:
|
||||
"""The *Sound…* row, as a ``(label, description, value)`` row for ``menu_rows``."""
|
||||
return (marked_label(SOUND_ICON, "Sound…", "", lane=lane), describe(ctx, key, kind), SOUND_ROW)
|
||||
|
||||
|
||||
async def pick_sound(ctx: AppContext, key: str, kind: str, subject: str) -> bool:
|
||||
"""Ask when the conversation plays a sound, and store the answer.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
key: The key of the conversation.
|
||||
kind: ``dm`` or ``room``.
|
||||
subject: The name of the conversation, for the title.
|
||||
|
||||
Returns:
|
||||
``True`` if the setting changed.
|
||||
"""
|
||||
own = ctx.sound_store.get(key)
|
||||
current = own or _DEFAULT
|
||||
default_label = SOUND_WHEN_CHOICES[_default_when(ctx, kind)]
|
||||
options = [(_DEFAULT, f"Default ({default_label})"), *SOUND_WHEN_CHOICES.items()]
|
||||
items = [
|
||||
Choice(title=label + (" (current)" if value == current else ""), value=value)
|
||||
for value, label in options
|
||||
]
|
||||
choice = await ctx.ui.select(
|
||||
f"Sound — {subject}",
|
||||
items,
|
||||
prompt=f"When this {'conversation' if kind == 'dm' else 'room'} plays a sound:",
|
||||
default=current,
|
||||
)
|
||||
if choice is None or choice == current:
|
||||
return False
|
||||
ctx.sound_store.set(key, None if choice == _DEFAULT else choice)
|
||||
return True
|
||||
@@ -112,19 +112,11 @@ from rich.text import Text
|
||||
|
||||
from ..core.connection import ContactNotOnDeviceError, DeviceCommandError
|
||||
from ..core.geo import haversine_km, usable_fix
|
||||
from ..core.models import (
|
||||
NODE_TYPE_LABELS,
|
||||
NODE_TYPE_REPEATER,
|
||||
NODE_TYPE_ROOM,
|
||||
Contact,
|
||||
conversation_key,
|
||||
is_direct_messageable,
|
||||
utcnow,
|
||||
)
|
||||
from ..core.models import NODE_TYPE_LABELS, NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact, utcnow
|
||||
from ..core.places import SOURCE_USER
|
||||
from ..platforms import Platform, on_platform
|
||||
from ..services.clock_offsets import node_offset, room_posts_blocked
|
||||
from . import conversation_sound, menus
|
||||
from . import menus
|
||||
from .device_route_screen import ACTION as DEVICE_ROUTE_ACTION
|
||||
from .device_route_screen import ICON as DEVICE_ROUTE_ICON
|
||||
from .device_route_screen import RouteEnv, open_device_route
|
||||
@@ -1848,12 +1840,6 @@ async def open_node_detail(
|
||||
# map (a roof, a tower), or a place for a node with no location at all.
|
||||
if places is not None and node_id:
|
||||
info_actions.append(_Action("place", "✎", "", "Set place…"))
|
||||
# The sound of the conversation with this node: a DM with a companion, or the board of a
|
||||
# room (refer to meshterm.ui.conversation_sound). Only where a sound can play.
|
||||
sound_kind = _sound_kind(ctx, contact, you, node_type)
|
||||
sound_key = _sound_key(contact) if sound_kind else None
|
||||
if sound_kind and sound_key:
|
||||
info_actions.append(_sound_action(ctx, sound_key, sound_kind))
|
||||
if you:
|
||||
# Our page is where the user looks at our node, so it offers the tools of the main
|
||||
# menu that act on our node: its whole ``This node`` section, row for row.
|
||||
@@ -2096,12 +2082,6 @@ async def open_node_detail(
|
||||
if await _restore_archived(ctx, contact, self_key, label):
|
||||
contact_removed = True
|
||||
break
|
||||
elif action == conversation_sound.SOUND_ROW:
|
||||
assert sound_kind and sound_key # offered only for a conversation
|
||||
if await conversation_sound.pick_sound(ctx, sound_key, sound_kind, label):
|
||||
fresh = _sound_action(ctx, sound_key, sound_kind)
|
||||
base_actions = [fresh if a.key == fresh.key else a for a in base_actions]
|
||||
screen.replace_info_actions(management(locked))
|
||||
elif action in ("lock", "unlock"):
|
||||
# No confirm and no notice. The same row that set the lock can reverse it,
|
||||
# and the change of the row into its opposite is the acknowledgement.
|
||||
@@ -2187,42 +2167,6 @@ def _shown_self(info: dict) -> tuple:
|
||||
return tuple(info.get(field) for field in _SHOWN_SELF_FIELDS)
|
||||
|
||||
|
||||
def _sound_kind(
|
||||
ctx: AppContext, contact: Contact | None, you: bool, node_type: int | None
|
||||
) -> str | None:
|
||||
"""The kind of the conversation with a node, for its sound row, or ``None`` for no row.
|
||||
|
||||
A companion is a DM, and a room server is a room. Our node, a node with no key, and a
|
||||
repeater or a sensor (which has no conversation) have no row. Nor does a platform that
|
||||
cannot play a sound.
|
||||
"""
|
||||
if you or contact is None or not conversation_sound.offered(ctx):
|
||||
return None
|
||||
if node_type == NODE_TYPE_ROOM:
|
||||
return "room"
|
||||
return "dm" if is_direct_messageable(node_type) else None
|
||||
|
||||
|
||||
def _sound_key(contact: Contact | None) -> str | None:
|
||||
"""The key of the conversation with a contact (``dm:<key prefix>``), or ``None``.
|
||||
|
||||
The key prefix is the first six bytes of the key, as the address of a direct message
|
||||
and the history use it (refer to :func:`~meshterm.core.models.conversation_key`).
|
||||
"""
|
||||
if contact is None:
|
||||
return None
|
||||
prefix = (contact.key_prefix or contact.public_key[:12] or "").lower()
|
||||
return conversation_key(False, None, prefix) if prefix else None
|
||||
|
||||
|
||||
def _sound_action(ctx: AppContext, key: str, kind: str) -> _Action:
|
||||
"""The sound row of the node page, with what the conversation plays now."""
|
||||
description = conversation_sound.describe(ctx, key, kind)
|
||||
return _Action(
|
||||
conversation_sound.SOUND_ROW, conversation_sound.SOUND_ICON, "", f"Sound — {description}…"
|
||||
)
|
||||
|
||||
|
||||
def _management_rows(
|
||||
*, locked: bool, lockable: bool, manageable: bool, archived: bool, whole_key: bool
|
||||
) -> list[_Action]:
|
||||
|
||||
+1
-10
@@ -48,8 +48,6 @@ from ..core.models import (
|
||||
is_room,
|
||||
)
|
||||
from ..platforms import get_platform
|
||||
from . import conversation_sound
|
||||
from .conversation_sound import SOUND_ICON, SOUND_ROW, sound_row
|
||||
from .menus import (
|
||||
Lane,
|
||||
column_header,
|
||||
@@ -497,8 +495,6 @@ async def _room_detail(ctx: AppContext, key: str) -> int:
|
||||
from .room import open_room
|
||||
|
||||
await open_room(ctx, Conversation(label=room.name, is_channel=False, contact=room))
|
||||
elif choice == SOUND_ROW:
|
||||
await conversation_sound.pick_sound(ctx, f"dm:{_peer(room)}", "room", room.name)
|
||||
elif choice == _FORGET:
|
||||
await _forget(ctx, room)
|
||||
elif choice == _DELETE:
|
||||
@@ -540,7 +536,7 @@ def _detail_items(ctx: AppContext, room: Contact) -> list:
|
||||
stored = bool(
|
||||
ctx.repo.recent_chat_messages(is_channel=False, peer=peer, posts_only=True, limit=1)
|
||||
)
|
||||
lane = icon_lane(("💬", "↻", "🔑", SOUND_ICON, "🗑"))
|
||||
lane = icon_lane(("💬", "↻", "🔑", "🗑"))
|
||||
unread = ctx.chat.unread(f"dm:{peer}")
|
||||
rows: list = []
|
||||
if joined:
|
||||
@@ -560,11 +556,6 @@ def _detail_items(ctx: AppContext, room: Contact) -> list:
|
||||
"Log in with a different password",
|
||||
_PASSWORD,
|
||||
),
|
||||
*(
|
||||
[sound_row(ctx, f"dm:{peer}", "room", lane)]
|
||||
if conversation_sound.offered(ctx)
|
||||
else []
|
||||
),
|
||||
(
|
||||
marked_label("🗑", "Forget this room…", "err", lane=lane),
|
||||
"Stop logging in, and forget its password",
|
||||
|
||||
+65
-96
@@ -11,7 +11,6 @@ import asyncio
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from rich.cells import cell_len
|
||||
@@ -2783,10 +2782,30 @@ async def test_badge_still_respects_a_muted_channel(tmp_path: Path, repo: Reposi
|
||||
# -- the sound of a received message -------------------------------------------------
|
||||
|
||||
|
||||
class _FakeSound:
|
||||
"""Records each event that the chat service asks to play, and follows the switches."""
|
||||
|
||||
def __init__(self, prefs: Preferences) -> None:
|
||||
"""Read the switches from ``prefs``."""
|
||||
from meshterm.services.sound import EVENT_PREFERENCE
|
||||
|
||||
self._prefs = prefs
|
||||
self._switch = EVENT_PREFERENCE
|
||||
self.events: list = []
|
||||
|
||||
def event_on(self, event) -> bool: # noqa: ANN001 - a SoundEvent
|
||||
"""The switch of the event."""
|
||||
return bool(self._prefs.get(self._switch[event]))
|
||||
|
||||
def notify(self, event) -> bool: # noqa: ANN001 - a SoundEvent
|
||||
"""Record the event when its switch is on, as the service does."""
|
||||
if self.event_on(event):
|
||||
self.events.append(event)
|
||||
return True
|
||||
|
||||
|
||||
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] = {
|
||||
@@ -2796,12 +2815,10 @@ async def _sound_chat(repo: Repository, tmp_path: Path, **prefs: object):
|
||||
}
|
||||
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)
|
||||
ctx.sound = _FakeSound(ctx.preferences)
|
||||
chat = ChatService(ctx)
|
||||
await chat.start()
|
||||
return device, ctx, chat, events
|
||||
return device, ctx, chat, ctx.sound.events
|
||||
|
||||
|
||||
def _public_key() -> str:
|
||||
@@ -2810,12 +2827,41 @@ def _public_key() -> str:
|
||||
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``)."""
|
||||
def _mute_public(ctx, tmp_path: Path) -> None:
|
||||
from meshterm.core.channels import channel_identity
|
||||
from meshterm.core.mute_store import MuteStore
|
||||
|
||||
ctx.mute_store = MuteStore(tmp_path / "mutes.json")
|
||||
ctx.mute_store.set_muted(channel_identity("Public", DEFAULT_PUBLIC_SECRET), True)
|
||||
|
||||
|
||||
async def test_sound_each_kind_plays_its_own_event(tmp_path: Path, repo: Repository) -> None:
|
||||
"""A DM, a channel message, and a mention each play their own event, by default."""
|
||||
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"))
|
||||
await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True))
|
||||
text = "Ann: hey @[MockCompanion]"
|
||||
await _record(chat, ctx, Message(text=text, channel=0, is_channel=True))
|
||||
assert events == [
|
||||
SoundEvent.DIRECT_MESSAGE,
|
||||
SoundEvent.CHANNEL_MESSAGE,
|
||||
SoundEvent.MENTION,
|
||||
]
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_sound_a_switched_off_event_is_silent(tmp_path: Path, repo: Repository) -> None:
|
||||
"""``sound_channel = off`` silences channel messages, and DMs still play."""
|
||||
from meshterm.services.sound import SoundEvent
|
||||
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path, sound_channel=False)
|
||||
try:
|
||||
await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True))
|
||||
await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7"))
|
||||
assert events == [SoundEvent.DIRECT_MESSAGE]
|
||||
finally:
|
||||
@@ -2823,63 +2869,22 @@ async def test_sound_a_dm_plays_by_default(tmp_path: Path, repo: Repository) ->
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_sound_a_channel_plays_only_for_a_mention_by_default(
|
||||
async def test_sound_a_mention_with_its_switch_off_plays_its_kind(
|
||||
tmp_path: Path, repo: Repository
|
||||
) -> None:
|
||||
"""A channel plays nothing for a plain message, and the mention sound for a mention."""
|
||||
"""With ``sound_mention`` off, a mention plays the sound of its kind instead."""
|
||||
from meshterm.services.sound import SoundEvent
|
||||
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path)
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path, sound_mention=False)
|
||||
try:
|
||||
await _record(chat, ctx, Message(text="Ann: hey all", channel=0, is_channel=True))
|
||||
assert events == []
|
||||
text = "Ann: hey @[MockCompanion]"
|
||||
text = "Ann: @[MockCompanion] look"
|
||||
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_dm_wins(tmp_path: Path, repo: Repository) -> None:
|
||||
"""The setting of one DM replaces the default of its kind: ``off`` silences it."""
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path)
|
||||
try:
|
||||
ctx.sound_store.set("dm:d4e5f6a7", "off")
|
||||
await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7"))
|
||||
assert events == []
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_sound_a_channel_has_no_setting_of_its_own(tmp_path: Path, repo: Repository) -> None:
|
||||
"""A channel follows ``channel_sound`` only. A record in the store changes nothing."""
|
||||
from meshterm.services.sound import SoundEvent
|
||||
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path, channel_sound="all")
|
||||
try:
|
||||
ctx.sound_store.set(_public_key(), "off") # an old record: ignored
|
||||
await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True))
|
||||
assert events == [SoundEvent.CHANNEL_MESSAGE]
|
||||
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)
|
||||
@@ -2892,54 +2897,18 @@ async def test_sound_the_open_conversation_is_silent(tmp_path: Path, repo: Repos
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def _muted_public(ctx, tmp_path: Path) -> None:
|
||||
from meshterm.core.channels import channel_identity
|
||||
from meshterm.core.mute_store import MuteStore
|
||||
|
||||
ctx.mute_store = MuteStore(tmp_path / "mutes.json")
|
||||
ctx.mute_store.set_muted(channel_identity("Public", DEFAULT_PUBLIC_SECRET), True)
|
||||
|
||||
|
||||
async def test_sound_a_muted_channel_is_silent(tmp_path: Path, repo: Repository) -> None:
|
||||
"""A mute turns off the notifications of a channel, and a sound is one (JP, 2026-11-21)."""
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path, channel_sound="all")
|
||||
try:
|
||||
await _muted_public(ctx, tmp_path)
|
||||
await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True))
|
||||
assert events == []
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_sound_a_mention_always_plays_by_default(tmp_path: Path, repo: Repository) -> None:
|
||||
"""``mention_sound_always`` (on) plays a mention on a muted channel and in an ``off`` DM."""
|
||||
from meshterm.services.sound import SoundEvent
|
||||
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path)
|
||||
try:
|
||||
await _muted_public(ctx, tmp_path)
|
||||
text = "Ann: @[MockCompanion] look"
|
||||
await _record(chat, ctx, Message(text=text, channel=0, is_channel=True))
|
||||
assert chat.unread(_public_key()) == 0
|
||||
ctx.sound_store.set("dm:d4e5f6a7", "off")
|
||||
await _record(chat, ctx, Message(text="@[MockCompanion] hi", sender="d4e5f6a7"))
|
||||
assert events == [SoundEvent.MENTION, SoundEvent.MENTION]
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_sound_without_the_override_a_muted_mention_is_silent(
|
||||
async def test_sound_a_muted_channel_is_silent_also_for_a_mention(
|
||||
tmp_path: Path, repo: Repository
|
||||
) -> None:
|
||||
"""With ``mention_sound_always`` off, a mention on a muted channel plays nothing."""
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path, mention_sound_always=False)
|
||||
"""A mute turns off all notifications of a channel, a mention included (JP, 2026-11-21)."""
|
||||
device, ctx, chat, events = await _sound_chat(repo, tmp_path)
|
||||
try:
|
||||
await _muted_public(ctx, tmp_path)
|
||||
_mute_public(ctx, tmp_path)
|
||||
await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True))
|
||||
text = "Ann: @[MockCompanion] look"
|
||||
await _record(chat, ctx, Message(text=text, channel=0, is_channel=True))
|
||||
assert events == []
|
||||
assert chat.unread(_public_key()) == 0
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The Sound row of a conversation, and its picker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from meshterm.core.preferences import Preferences
|
||||
from meshterm.core.sound_store import SoundStore
|
||||
from meshterm.ui import conversation_sound
|
||||
from meshterm.ui.node_detail_screen import _sound_key, _sound_kind
|
||||
|
||||
|
||||
class FakeUi:
|
||||
"""Answers the picker with a fixed value, and records what it asked."""
|
||||
|
||||
def __init__(self, answer: object) -> None:
|
||||
"""Answer each select with ``answer``."""
|
||||
self.answer = answer
|
||||
self.asked: list[tuple[str, list, object]] = []
|
||||
|
||||
async def select(self, title: str, items: list, *, prompt: str, default: object) -> object:
|
||||
"""Record the question, and return the fixed answer."""
|
||||
self.asked.append((title, items, default))
|
||||
return self.answer
|
||||
|
||||
|
||||
def _ctx(tmp_path: Path, answer: object = None, **prefs: object) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
preferences=Preferences(values=prefs),
|
||||
sound_store=SoundStore(tmp_path / "sounds.json"),
|
||||
sound=SimpleNamespace(available=True),
|
||||
ui=FakeUi(answer),
|
||||
)
|
||||
|
||||
|
||||
def test_the_description_names_the_default_or_the_own_setting(tmp_path: Path) -> None:
|
||||
"""With no setting, the row names the default of the kind. With one, it names it."""
|
||||
ctx = _ctx(tmp_path)
|
||||
assert conversation_sound.describe(ctx, "dm:a", "room") == "Default: mentions only"
|
||||
assert conversation_sound.describe(ctx, "dm:b", "dm") == "Default: every message"
|
||||
ctx.sound_store.set("dm:a", "off")
|
||||
assert conversation_sound.describe(ctx, "dm:a", "room") == "No sound"
|
||||
|
||||
|
||||
def test_the_picker_stores_a_setting_and_default_removes_it(tmp_path: Path) -> None:
|
||||
"""A pick stores the setting. ``Default`` removes it again."""
|
||||
ctx = _ctx(tmp_path, answer="all")
|
||||
assert asyncio.run(conversation_sound.pick_sound(ctx, "dm:a", "room", "Board"))
|
||||
assert ctx.sound_store.get("dm:a") == "all"
|
||||
title, items, default = ctx.ui.asked[0]
|
||||
assert title == "Sound — Board"
|
||||
assert default == "default"
|
||||
assert [i.value for i in items] == ["default", "off", "mentions", "all"]
|
||||
ctx.ui.answer = "default"
|
||||
assert asyncio.run(conversation_sound.pick_sound(ctx, "dm:a", "room", "Board"))
|
||||
assert ctx.sound_store.get("dm:a") is None
|
||||
|
||||
|
||||
def test_esc_or_the_same_value_changes_nothing(tmp_path: Path) -> None:
|
||||
"""Esc (``None``) and the current value both return ``False`` and write nothing."""
|
||||
ctx = _ctx(tmp_path, answer=None)
|
||||
assert not asyncio.run(conversation_sound.pick_sound(ctx, "dm:b", "dm", "Ann"))
|
||||
ctx.ui.answer = "default"
|
||||
assert not asyncio.run(conversation_sound.pick_sound(ctx, "dm:b", "dm", "Ann"))
|
||||
assert not (tmp_path / "sounds.json").exists()
|
||||
|
||||
|
||||
def test_the_row_is_only_where_a_sound_can_play(tmp_path: Path) -> None:
|
||||
"""No sound service, or one that cannot play, means no row."""
|
||||
ctx = _ctx(tmp_path)
|
||||
assert conversation_sound.offered(ctx)
|
||||
ctx.sound.available = False
|
||||
assert not conversation_sound.offered(ctx)
|
||||
assert not conversation_sound.offered(SimpleNamespace())
|
||||
|
||||
|
||||
def test_the_node_page_offers_the_row_for_a_companion_and_a_room(tmp_path: Path) -> None:
|
||||
"""A companion is a DM, a room server is a room, and a repeater has no conversation."""
|
||||
ctx = _ctx(tmp_path)
|
||||
contact = SimpleNamespace(key_prefix="D4E5F6A7B8C9", public_key="d4e5f6a7b8c9" + "0" * 52)
|
||||
assert _sound_kind(ctx, contact, False, 1) == "dm"
|
||||
assert _sound_kind(ctx, contact, False, 3) == "room"
|
||||
assert _sound_kind(ctx, contact, False, 2) is None
|
||||
assert _sound_kind(ctx, contact, True, 1) is None # our own node
|
||||
assert _sound_key(contact) == "dm:d4e5f6a7b8c9"
|
||||
@@ -301,3 +301,28 @@ def test_no_tick_is_scheduled_when_the_tick_is_off(tmp_path: Path) -> None:
|
||||
return service._tick_pending
|
||||
|
||||
assert asyncio.run(run()) is False
|
||||
|
||||
|
||||
def test_each_event_has_a_switch_on_by_default_except_the_tick() -> None:
|
||||
"""Each event names a preference. All are on by default, except the packet tick."""
|
||||
from meshterm.core.preferences import get_spec
|
||||
from meshterm.services.sound import EVENT_PREFERENCE
|
||||
|
||||
assert set(EVENT_PREFERENCE) == set(SoundEvent)
|
||||
for event, key in EVENT_PREFERENCE.items():
|
||||
assert get_spec(key).default is (event is not SoundEvent.PACKET_TICK)
|
||||
|
||||
|
||||
def test_a_switched_off_event_plays_nothing_and_does_not_flash(tmp_path: Path) -> None:
|
||||
"""An event that its switch turns off does nothing at all."""
|
||||
service, player, _, flashes, _ = _service(tmp_path, sound_dm=False)
|
||||
assert service.notify(SoundEvent.DIRECT_MESSAGE) is False
|
||||
assert player.played == [] and flashes == []
|
||||
assert service.notify(SoundEvent.ROOM_POST) is True
|
||||
|
||||
|
||||
def test_the_battery_switch_silences_the_battery_sound(tmp_path: Path) -> None:
|
||||
"""With ``sound_battery`` off, a low battery plays nothing."""
|
||||
service, player, _, _, _ = _service(tmp_path, sound_battery=False)
|
||||
service.note_battery(10, charging=False)
|
||||
assert player.played == []
|
||||
@@ -1,53 +0,0 @@
|
||||
# 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"}
|
||||
Reference in new issue
Block a user