fix(irc): accept a channel setting written with its # prefix (#1722)

The IRC channel setting asks for the name without the `#`, and the
client adds it when it joins. Mine was stored as `#ebooks`, so Shelfmark
joined `##ebooks`, a different and nearly empty channel. The log said
`Joined ##ebooks - 1 servers online`, every search came back empty, and
nothing in the UI said why. With `ebooks` the same search joined
`#ebooks` with 26 servers and returned 9 results.

This strips whitespace and leading `#` where the two channel settings
are read: the release source (availability, search channel, audiobook
channel) and the download handler, which reads `IRC_CHANNEL` on its own.
The join, the message target and the cache key all get the bare name.

Tests are in `tests/irc/test_source.py` (main and audiobook channel) and
a new `tests/irc/test_handler.py`. With the source change reverted all
three fail (`assert '#ebooks' == 'ebooks'`). `make python-checks` is
clean.

One thing I left alone: the download handler always uses `IRC_CHANNEL`,
never `IRC_AUDIOBOOK_CHANNEL`, so an audiobook found in a separate
audiobook channel is requested in the main one.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* IRC channel settings now work consistently whether entered with or
without a leading `#`. Surrounding whitespace is also handled, helping
searches, audiobook routing, and downloads use the intended channel.
* Downloads connect using the normalized channel name while keeping the
channel request correctly formatted.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
David Lacroix authored and GitHub committed 2026-11-15 18:27:14 -05:00
1 parent 2526bd7287
commit 5472c36c56
5 files changed
+134 -6

No files matched your search

+10
View File
@@ -72,6 +72,16 @@ def has_control_characters(value: str) -> bool:
return any((ord(char) < 0x20 and char != "\x01") or ord(char) == 0x7F for char in value)
def bare_channel_name(value: str) -> str:
"""Return a channel setting without the leading # the client adds itself.
The settings ask for the name without the prefix, but "#ebooks" is how a channel is
written everywhere else. Taken as is, it joined "##ebooks", a different and nearly
empty channel, and every search came back empty without an error.
"""
return value.strip().lstrip("#").strip()
class IRCConnectionError(IRCError):
"""Connection failed."""
+2 -2
View File
@@ -11,7 +11,7 @@ from shelfmark.core.config import config
from shelfmark.core.logger import setup_logger
from shelfmark.release_sources import DownloadHandler, register_handler
from .client import has_control_characters
from .client import bare_channel_name, has_control_characters
from .connection_manager import connection_manager
from .dcc import DCCError, download_dcc, safe_dcc_filename
@@ -92,7 +92,7 @@ class IRCDownloadHandler(DownloadHandler):
server = _config_text("IRC_SERVER")
port = _config_port("IRC_PORT", 6697)
use_tls = _config_bool("IRC_USE_TLS", True)
channel = _config_text("IRC_CHANNEL")
channel = bare_channel_name(_config_text("IRC_CHANNEL"))
nick = _config_text("IRC_NICK")
if not server or not channel or not nick:
+9 -4
View File
@@ -31,7 +31,7 @@ from shelfmark.release_sources import (
register_source,
)
from .client import has_control_characters
from .client import bare_channel_name, has_control_characters
from .connection_manager import connection_manager
from .dcc import DCCError, download_dcc, safe_dcc_filename
from .parser import SearchResult, extract_results_from_zip, parse_results_file
@@ -47,6 +47,11 @@ def _config_text(key: str) -> str:
return str(value).strip()
def _config_channel(key: str) -> str:
"""Read a channel setting as the bare name, so "#ebooks" and "ebooks" are one channel."""
return bare_channel_name(_config_text(key))
def _config_port(key: str, default: int) -> int:
"""Read an IRC port value from config, accepting ints and numeric strings."""
value = config.get(key, default)
@@ -179,7 +184,7 @@ class IRCReleaseSource(ReleaseSource):
to the channel, which reads as spam and gets the nick banned.
"""
server = _config_text("IRC_SERVER")
channel = _config_text("IRC_CHANNEL")
channel = _config_channel("IRC_CHANNEL")
nick = _config_text("IRC_NICK")
search_bot = _config_text("IRC_SEARCH_BOT")
return bool(server and channel and nick and search_bot)
@@ -257,7 +262,7 @@ class IRCReleaseSource(ReleaseSource):
server = _config_text("IRC_SERVER")
port = _config_port("IRC_PORT", 6697)
use_tls = _config_bool("IRC_USE_TLS", True)
channel = _config_text("IRC_CHANNEL")
channel = _config_channel("IRC_CHANNEL")
nick = _config_text("IRC_NICK")
search_bot = _config_text("IRC_SEARCH_BOT")
@@ -267,7 +272,7 @@ class IRCReleaseSource(ReleaseSource):
# fall back to the main channel/bot — that is the common case, since most networks
# (irchighway included) serve both formats from the one channel.
if is_audiobook(content_type):
audiobook_channel = _config_text("IRC_AUDIOBOOK_CHANNEL")
audiobook_channel = _config_channel("IRC_AUDIOBOOK_CHANNEL")
if audiobook_channel:
channel = audiobook_channel
audiobook_search_bot = _config_text("IRC_AUDIOBOOK_SEARCH_BOT")
+27
View File
@@ -0,0 +1,27 @@
"""What the IRC download handler joins and where it sends the request line."""
from threading import Event
from unittest.mock import MagicMock
from shelfmark.core.models import DownloadTask
from shelfmark.release_sources.irc import handler as irc_handler
def test_download_with_hash_prefixed_channel_setting_uses_the_bare_channel(monkeypatch):
"""A stored "#ebooks" sent the download request to "##ebooks", where no bot answers.
The handler reads IRC_CHANNEL itself, so it needs the same normalisation as search.
"""
client = MagicMock()
client.wait_for_dcc.return_value = None
manager = MagicMock()
manager.get_connection.return_value = client
monkeypatch.setattr(irc_handler, "connection_manager", manager)
values = {"IRC_SERVER": "irc.example.test", "IRC_CHANNEL": "#ebooks", "IRC_NICK": "reader"}
monkeypatch.setattr(irc_handler.config, "get", lambda key, default="": values.get(key, default))
task = DownloadTask(task_id="!bot Author - Title.epub", source="irc", title="t")
irc_handler.IRCDownloadHandler().download(task, Event(), lambda _p: None, lambda _s, _m: None)
assert manager.get_connection.call_args.kwargs["channel"] == "ebooks"
client.send_message.assert_called_once_with("#ebooks", "!bot Author - Title.epub")
+86
View File
@@ -419,3 +419,89 @@ def test_search_send_budget_blocks_repost_and_returns_cache(monkeypatch):
assert releases == [cached_release]
assert source._online_servers == {"AudioBot"}
def _search_once(monkeypatch, settings: dict[str, str], content_type: str = "ebook"):
"""Run one uncached search and return what it joined, sent and cached."""
import shelfmark.release_sources.irc.source as irc_source
source = IRCReleaseSource()
connection_kwargs: dict[str, object] = {}
cache_keys: list[str] = []
class FakeClient:
online_servers: set[str] = set()
def send_message(self, channel: str, message: str) -> None:
self.channel = channel
self.message = message
def wait_for_dcc(
self, *, timeout: float, result_type: bool, expected_senders: object = None
) -> None:
return None
client = FakeClient()
monkeypatch.setattr(irc_source, "_config_text", lambda key: settings.get(key, ""))
irc_source._recent_message_sends.clear()
monkeypatch.setattr(source, "is_available", lambda: True)
monkeypatch.setattr(irc_source, "_enforce_rate_limit", lambda: None)
monkeypatch.setattr(irc_source, "_emit_status", lambda *_args, **_kwargs: None)
monkeypatch.setattr(
"shelfmark.release_sources.irc.cache.get_cached_results",
lambda cache_key, *_args, **_kwargs: None,
)
monkeypatch.setattr(
"shelfmark.release_sources.irc.cache.cache_results",
lambda cache_key, title, releases, *, online_servers=None: cache_keys.append(cache_key),
)
def fake_get_connection(**kwargs: object) -> FakeClient:
connection_kwargs.update(kwargs)
return client
monkeypatch.setattr(
"shelfmark.release_sources.irc.connection_manager.connection_manager.get_connection",
fake_get_connection,
)
monkeypatch.setattr(
"shelfmark.release_sources.irc.connection_manager.connection_manager.release_connection",
lambda _client: None,
)
book = BookMetadata(provider="hardcover", provider_id="1", title="Some Book")
source.search(book, _plan("Some Book"), content_type=content_type)
return connection_kwargs["channel"], client.channel, cache_keys
_BASE_SETTINGS = {
"IRC_SERVER": "irc.example.net",
"IRC_NICK": "tester",
"IRC_SEARCH_BOT": "search",
}
def test_channel_setting_with_hash_prefix_joins_the_same_channel(monkeypatch):
"""A stored "#ebooks" joined "##ebooks", an almost empty channel, and found nothing.
The setting asks for the name without the #, but that is not how people write a
channel, and nothing reported the mistake.
"""
bare = _search_once(monkeypatch, {**_BASE_SETTINGS, "IRC_CHANNEL": "ebooks"})
prefixed = _search_once(monkeypatch, {**_BASE_SETTINGS, "IRC_CHANNEL": " #ebooks "})
assert prefixed == bare
assert prefixed == ("ebooks", "#ebooks", ["irc.example.net:ebooks:some book"])
def test_audiobook_channel_setting_with_hash_prefix_joins_the_same_channel(monkeypatch):
"""The audiobook channel is read the same way as the main one, so it had the same trap."""
settings = {**_BASE_SETTINGS, "IRC_CHANNEL": "ebooks"}
bare = _search_once(monkeypatch, {**settings, "IRC_AUDIOBOOK_CHANNEL": "bookz"}, "audiobook")
prefixed = _search_once(
monkeypatch, {**settings, "IRC_AUDIOBOOK_CHANNEL": "#bookz"}, "audiobook"
)
assert prefixed == bare
assert prefixed == ("bookz", "#bookz", ["irc.example.net:bookz:some book"])