mirror of
https://github.com/calibrain/shelfmark.git
synced 2026-11-21 13:56:41 +00:00
Some Soulseek uploaders run a bot that blocks your downloads until you
type a word to them in a private message ("please type 'download' in
this chat"). The files sit queued until someone answers, and nobody
looking at Shelfmark would know why.
While a slskd download is polling, this checks slskd's unacknowledged
private messages about once a minute, replies with the word the message
asks for and marks the conversation read. It only matches three known
phrasings, the word has to fit `[A-Za-z0-9_-]{1,24}`, and each user gets
at most one reply per 12 hours (recorded after a successful send). Every
reply is logged at INFO.
The challenge patterns and the one-reply-per-12-hours idea come from
@Nezreka's [SoulSync](https://github.com/Nezreka/SoulSync)
(`core/chat_autoprove.py`, commit 445473b, MIT). I reworked it for
slskd's client and this download handler. The credit is in the module
docstring and the commit message too.
This sends messages to other people on your behalf without asking, so
the setting `SLSKD_CHAT_AUTOPROVE` is off by default here. Say if you'd
rather it not exist at all, or want it somewhere other than the slskd
settings.
It has run on my instance since October 22 without seeing a real
challenge, so the reply path is covered by tests but not by a live one.
The same code works in nezreka/soulsync with the same slskd client so I
am confident in it. Ruff, basedpyright and the slskd tests pass, and
`docs/environment-variables.md` and the readme line for slskd are
updated.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added an optional setting to automatically answer supported Soulseek
private-message challenges while a download is running. When enabled,
Shelfmark checks unread messages, replies to each person at most once
every 12 hours, logs replies, and marks answered conversations as read.
The setting is off by default.
* **Documentation**
* Updated the environment-variable and Soulseek setup documentation with
details about the setting and its behavior, including a reminder to
leave it off if you read slskd messages yourself.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
332 lines
12 KiB
Python
332 lines
12 KiB
Python
"""Unit tests for the slskd anti-leech chat challenge responder."""
|
|
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
import requests
|
|
|
|
from shelfmark.release_sources.slskd import handler as handler_module
|
|
from shelfmark.release_sources.slskd.api import SlskdClient, SlskdError
|
|
from shelfmark.release_sources.slskd.chat_autoprove import (
|
|
COOLDOWN_SECONDS,
|
|
SCAN_BUDGET_SECONDS,
|
|
ChatAutoProver,
|
|
extract_token,
|
|
scan_and_respond,
|
|
)
|
|
|
|
# ── helpers ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def _convo(username="peer", *, unread=True):
|
|
return {"username": username, "hasUnAcknowledgedMessages": unread}
|
|
|
|
|
|
def _msg(text, *, direction="In", acknowledged=False):
|
|
return {"direction": direction, "acknowledged": acknowledged, "message": text}
|
|
|
|
|
|
def _client(conversations, messages_by_user):
|
|
client = MagicMock(spec=SlskdClient)
|
|
client.list_conversations.return_value = conversations
|
|
client.get_conversation.side_effect = lambda u: {
|
|
"username": u,
|
|
"messages": messages_by_user.get(u, []),
|
|
}
|
|
return client
|
|
|
|
|
|
CHALLENGE = "ProveIt: To prove you are human, please type 'download' in this chat."
|
|
|
|
# ── token extraction ───────────────────────────────────────────────────────────
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("text", "token"),
|
|
[
|
|
(CHALLENGE, "download"),
|
|
('please type "human" in chat to be whitelisted', "human"),
|
|
('Please reply with "human" to be added to my whitelist', "human"),
|
|
("reply open_sesame to get access", "open_sesame"),
|
|
('say "ok-1" in chat', "ok-1"),
|
|
("SAY hello TO be added", "hello"),
|
|
("say human in the chat", "human"),
|
|
],
|
|
)
|
|
def test_extract_token_known_phrasings(text, token):
|
|
assert extract_token(text) == token
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"text",
|
|
[
|
|
"",
|
|
None,
|
|
"thanks for downloading!",
|
|
"i will type the title in a minute",
|
|
f"please type '{'a' * 25}' in this chat",
|
|
"please type 'rm -rf /' in this chat",
|
|
"please type 'bad;word' in this chat",
|
|
"reply with 'x y' to be added",
|
|
"I would say thanks to everyone",
|
|
"say hello to me",
|
|
"just say yes to the next one",
|
|
],
|
|
)
|
|
def test_extract_token_ignores_non_challenges(text):
|
|
assert extract_token(text) is None
|
|
|
|
|
|
# ── scan_and_respond ───────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_replies_with_token_and_acknowledges():
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
state: dict[str, float] = {}
|
|
|
|
replies = scan_and_respond(client, state, now=100.0)
|
|
|
|
assert replies == [("peer", "download")]
|
|
client.send_private_message.assert_called_once_with("peer", "download")
|
|
client.acknowledge_conversation.assert_called_once_with("peer")
|
|
assert state == {"peer": 100.0}
|
|
|
|
|
|
def test_acknowledge_happens_after_send():
|
|
order = []
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
client.send_private_message.side_effect = lambda *a: order.append("send")
|
|
client.acknowledge_conversation.side_effect = lambda *a: order.append("ack")
|
|
|
|
scan_and_respond(client, {}, now=1.0)
|
|
|
|
assert order == ["send", "ack"]
|
|
|
|
|
|
def test_cooldown_blocks_second_reply_until_it_expires():
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
state: dict[str, float] = {}
|
|
|
|
assert scan_and_respond(client, state, now=0.0)
|
|
assert scan_and_respond(client, state, now=COOLDOWN_SECONDS - 1) == []
|
|
assert scan_and_respond(client, state, now=COOLDOWN_SECONDS + 1) == [("peer", "download")]
|
|
assert client.send_private_message.call_count == 2
|
|
|
|
|
|
def test_only_unacknowledged_inbound_messages_are_answered():
|
|
client = _client(
|
|
[_convo()],
|
|
{
|
|
"peer": [
|
|
_msg(CHALLENGE, acknowledged=True),
|
|
_msg(CHALLENGE, direction="Out"),
|
|
]
|
|
},
|
|
)
|
|
assert scan_and_respond(client, {}, now=0.0) == []
|
|
client.send_private_message.assert_not_called()
|
|
|
|
|
|
def test_conversation_without_unread_flag_is_not_fetched():
|
|
client = _client([_convo(unread=False)], {"peer": [_msg(CHALLENGE)]})
|
|
assert scan_and_respond(client, {}, now=0.0) == []
|
|
client.get_conversation.assert_not_called()
|
|
|
|
|
|
def test_unread_count_alone_marks_a_conversation_unread():
|
|
convo = {"username": "peer", "unAcknowledgedMessageCount": 2}
|
|
client = _client([convo], {"peer": [_msg(CHALLENGE)]})
|
|
assert scan_and_respond(client, {}, now=0.0) == [("peer", "download")]
|
|
|
|
|
|
def test_send_failure_does_not_record_cooldown_or_acknowledge():
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
client.send_private_message.side_effect = SlskdError("boom")
|
|
state: dict[str, float] = {}
|
|
|
|
assert scan_and_respond(client, state, now=0.0) == []
|
|
|
|
assert state == {}
|
|
client.acknowledge_conversation.assert_not_called()
|
|
# The next pass may try again.
|
|
client.send_private_message.side_effect = None
|
|
assert scan_and_respond(client, state, now=1.0) == [("peer", "download")]
|
|
|
|
|
|
def test_acknowledge_failure_keeps_the_reply_and_cooldown():
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
client.acknowledge_conversation.side_effect = requests.exceptions.ConnectionError()
|
|
state: dict[str, float] = {}
|
|
|
|
assert scan_and_respond(client, state, now=5.0) == [("peer", "download")]
|
|
assert state == {"peer": 5.0}
|
|
|
|
|
|
def test_one_failing_conversation_does_not_stop_the_others():
|
|
client = _client(
|
|
[_convo("a"), _convo("b")],
|
|
{"a": [_msg(CHALLENGE)], "b": [_msg(CHALLENGE)]},
|
|
)
|
|
client.send_private_message.side_effect = [SlskdError("no"), None]
|
|
|
|
assert scan_and_respond(client, {}, now=0.0) == [("b", "download")]
|
|
|
|
|
|
def test_slskd_timing_out_ends_the_pass():
|
|
client = _client(
|
|
[_convo("a"), _convo("b")],
|
|
{"a": [_msg(CHALLENGE)], "b": [_msg(CHALLENGE)]},
|
|
)
|
|
client.get_conversation.side_effect = requests.exceptions.Timeout()
|
|
|
|
assert scan_and_respond(client, {}, now=0.0) == []
|
|
assert client.get_conversation.call_count == 1
|
|
|
|
|
|
def test_scan_stops_reading_conversations_once_its_budget_is_spent():
|
|
client = _client(
|
|
[_convo("a"), _convo("b"), _convo("c")],
|
|
{"a": [_msg(CHALLENGE)], "b": [_msg(CHALLENGE)], "c": [_msg(CHALLENGE)]},
|
|
)
|
|
ticks = iter([1.0, 11.0])
|
|
|
|
replies = scan_and_respond(client, {}, now=0.0, clock=lambda: next(ticks), budget=10.0)
|
|
|
|
assert replies == [("a", "download")]
|
|
assert client.get_conversation.call_count == 1
|
|
|
|
|
|
def test_a_later_pass_resumes_after_the_last_conversation_read():
|
|
"""Unread chats that are not challenges cannot crowd out a challenge further down."""
|
|
conversations = [_convo("a"), _convo("b"), _convo("c")]
|
|
client = _client(conversations, {"a": [_msg("hi")], "b": [_msg("hey")], "c": [_msg(CHALLENGE)]})
|
|
progress: dict[str, str] = {}
|
|
|
|
def one_read_per_pass(ticks):
|
|
"""A clock that spends the budget after the first conversation of a pass."""
|
|
values = iter(ticks)
|
|
return lambda: next(values)
|
|
|
|
first = scan_and_respond(
|
|
client, {}, now=0.0, clock=one_read_per_pass([0.0, 11.0]), budget=10.0, progress=progress
|
|
)
|
|
second = scan_and_respond(
|
|
client, {}, now=0.0, clock=one_read_per_pass([0.0, 11.0]), budget=10.0, progress=progress
|
|
)
|
|
third = scan_and_respond(
|
|
client, {}, now=0.0, clock=one_read_per_pass([0.0, 11.0]), budget=10.0, progress=progress
|
|
)
|
|
|
|
assert (first, second) == ([], [])
|
|
assert third == [("c", "download")]
|
|
|
|
|
|
def test_the_pass_order_wraps_round():
|
|
"""After the last conversation, the next pass starts again at the first."""
|
|
client = _client([_convo("a"), _convo("b")], {"a": [_msg(CHALLENGE)]})
|
|
|
|
replies = scan_and_respond(client, {}, now=0.0, progress={"last": "b"})
|
|
|
|
assert replies == [("a", "download")]
|
|
|
|
|
|
def test_reply_is_logged():
|
|
client = _client([_convo()], {"peer": [_msg(CHALLENGE)]})
|
|
with patch("shelfmark.release_sources.slskd.chat_autoprove.logger") as log:
|
|
scan_and_respond(client, {}, now=0.0)
|
|
log.info.assert_called_once()
|
|
assert log.info.call_args.args[1:] == ("download", "peer")
|
|
|
|
|
|
# ── ChatAutoProver ─────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_prover_scans_at_most_once_per_interval():
|
|
"""A second call inside the interval does not scan; one after it does."""
|
|
client = _client([], {})
|
|
prover = ChatAutoProver(interval=60)
|
|
clock = iter([0.0, 30.0, 61.0])
|
|
|
|
for _ in range(3):
|
|
prover.maybe_scan(lambda: client, lambda: next(clock))
|
|
|
|
assert client.list_conversations.call_count == 2
|
|
|
|
|
|
def test_prover_runs_one_scan_at_a_time():
|
|
prover = ChatAutoProver(interval=60)
|
|
inner = MagicMock(spec=SlskdClient)
|
|
inner.list_conversations.return_value = []
|
|
|
|
def get_client_mid_scan():
|
|
# Another download thread polls while this scan is still running, past the interval.
|
|
assert prover.maybe_scan(lambda: inner, lambda: 120.0) == []
|
|
return inner
|
|
|
|
prover.maybe_scan(get_client_mid_scan, lambda: 0.0)
|
|
|
|
assert inner.list_conversations.call_count == 1
|
|
|
|
|
|
def test_prover_gives_each_scan_a_budget():
|
|
prover = ChatAutoProver()
|
|
with patch(
|
|
"shelfmark.release_sources.slskd.chat_autoprove.scan_and_respond", return_value=[]
|
|
) as scan:
|
|
prover.maybe_scan(lambda: MagicMock(spec=SlskdClient), lambda: 0.0)
|
|
assert scan.call_args.kwargs["budget"] == SCAN_BUDGET_SECONDS
|
|
|
|
|
|
def test_prover_survives_a_malformed_reply_from_slskd():
|
|
"""A reply the scan cannot read is logged, never raised into the download polling it."""
|
|
client = _client([_convo()], {})
|
|
client.get_conversation.side_effect = lambda _u: {"messages": 5}
|
|
prover = ChatAutoProver()
|
|
|
|
with patch("shelfmark.release_sources.slskd.chat_autoprove.logger") as log:
|
|
assert prover.maybe_scan(lambda: client, lambda: 0.0) == []
|
|
log.exception.assert_called_once()
|
|
assert prover.maybe_scan(lambda: client, lambda: 120.0) == [] # and the next scan still runs
|
|
assert client.list_conversations.call_count == 2
|
|
|
|
|
|
def test_prover_is_quiet_when_slskd_is_unreachable():
|
|
client = MagicMock(spec=SlskdClient)
|
|
client.list_conversations.side_effect = requests.exceptions.ConnectionError()
|
|
prover = ChatAutoProver()
|
|
|
|
assert prover.maybe_scan(lambda: client, lambda: 0.0) == []
|
|
|
|
|
|
def test_prover_skips_when_no_client_configured():
|
|
assert ChatAutoProver().maybe_scan(lambda: None, lambda: 0.0) == []
|
|
|
|
|
|
# ── handler wiring / setting ───────────────────────────────────────────────────
|
|
|
|
|
|
def _handler():
|
|
return handler_module.SlskdHandler()
|
|
|
|
|
|
def test_handler_scans_when_setting_is_on():
|
|
client = MagicMock(spec=SlskdClient)
|
|
with (
|
|
patch.object(handler_module, "_bool_setting", return_value=True),
|
|
patch.object(handler_module._CHAT_AUTOPROVER, "maybe_scan") as scan,
|
|
):
|
|
_handler()._answer_chat_challenges(client)
|
|
scan.assert_called_once()
|
|
|
|
|
|
def test_handler_does_nothing_when_setting_is_off():
|
|
client = MagicMock(spec=SlskdClient)
|
|
with (
|
|
patch.object(handler_module, "_bool_setting", return_value=False) as setting,
|
|
patch.object(handler_module._CHAT_AUTOPROVER, "maybe_scan") as scan,
|
|
):
|
|
_handler()._answer_chat_challenges(client)
|
|
setting.assert_called_once_with("SLSKD_CHAT_AUTOPROVE", False)
|
|
scan.assert_not_called()
|
|
client.list_conversations.assert_not_called()
|