diff --git a/AGENTS.md b/AGENTS.md index 2e7088a7..7a8cf7e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,6 +106,10 @@ See [AI_POLICY.md](AI_POLICY.md) for the contribution policy around AI tooling. applied to the raw API dictionaries before they become `Station` objects. Tests run without them (the autouse `corrections` fixture); add to that fixture to test with one. `test_corrections.py` validates the shipped files. +- `stations()` and `search()` drop duplicate streams (`without_duplicates`, + keyed by `stream_key`), after the corrections are applied. Lookups by UUID + and `stations_by_url()` never do, so saved stations keep working. Duplicates + are handled there, not as deletions in the corrections data. ## Where to read next diff --git a/README.md b/README.md index 932fcbe2..e525bd28 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,27 @@ RadioBrowser(user_agent="MyAwesomeApp/1.0.0", corrections=False) Found a station with wrong data? See [CONTRIBUTING.md](.github/CONTRIBUTING.md#correcting-station-data) for how to add a correction. +### Duplicate stations + +Many streams are listed more than once, added again by someone who could not +edit the existing station. `stations()` and `search()` return one station per +stream: the one with the most votes, then the most clicks, in the place where +that stream first shows up in the results. Streams count as the same when only +the scheme, the case of the host name, or a trailing `/` or `/;` differs. + +Looking a station up by its UUID, with `station()` or `stations_by_uuid()`, +still finds every one of them, so a station someone saved keeps working. +`stations_by_url()` returns every station with that stream too, as that is what +it is for. + +Only the duplicates within one response are found, so a page of results can be +shorter than `limit`, and two copies on different pages both show up. To get +every station, turn it off: + +```python +RadioBrowser(user_agent="MyAwesomeApp/1.0.0", deduplicate=False) +``` + ### Connection options ```python @@ -229,6 +250,7 @@ RadioBrowser( user_agent="MyAwesomeApp/1.0.0", # required, identifies your app request_timeout=8.0, # per-request timeout in seconds corrections=True, # apply the station corrections this library ships + deduplicate=True, # return one station per stream in lists ) ``` diff --git a/src/radios/radio_browser.py b/src/radios/radio_browser.py index 9926ad54..20032753 100644 --- a/src/radios/radio_browser.py +++ b/src/radios/radio_browser.py @@ -165,6 +165,61 @@ def stations_from_json( return [Station.from_dict(station) for station in stations] +def stream_key(url: str) -> str: + """Return a key for a stream URL, the same for every way to write it. + + The scheme, the case of the host name, and a trailing "/" or "/;" (an old + Shoutcast trick) do not change the stream. The path does, so its case is + kept. + + Args: + ---- + url: The stream URL. + + Returns: + ------- + The key, the same for URLs that point to the same stream. + + """ + address = url.strip().split("://", 1)[-1] + host, _, path = address.partition("/") + path = path.removesuffix(";").rstrip("/") + return f"{host.lower()}/{path}" + + +def without_duplicates(stations: list[Station]) -> list[Station]: + """Keep one station per stream: the one with the most votes, then clicks. + + The station that stays takes the place of the first one with its stream, + so the order of the results holds. + + Args: + ---- + stations: The stations, in the order of the results. + + Returns: + ------- + The stations, without the duplicates. + + """ + # Without a stream URL, there is nothing to compare a station on. + keys = [ + stream_key(station.url) if station.url else station.uuid for station in stations + ] + + best: dict[str, Station] = {} + for key, station in zip(keys, stations, strict=True): + current = best.get(key) + if current is None or (station.votes, station.click_count) > ( + current.votes, + current.click_count, + ): + best[key] = station + + # dict.fromkeys keeps the order in which each stream first shows up. + return [best[key] for key in dict.fromkeys(keys)] + + def name_filter_uri(uri: str, name: str | None) -> str: """Add a name filter to the URI of a list endpoint. @@ -239,6 +294,9 @@ class RadioBrowser: # Apply the corrections this library ships for the station data. Turn # them off to get the stations exactly as the API returns them. corrections: bool = True + # Return one station per stream in lists, the one with the most votes. + # Looking a station up by its UUID still finds every one of them. + deduplicate: bool = True _close_session: bool = False _host: str | None = None @@ -254,6 +312,10 @@ def _corrections(self) -> dict[str, dict[str, Any]]: """Return the corrections to apply, none when they are turned off.""" return CORRECTIONS if self.corrections else {} + def _station_list(self, stations: list[Station]) -> list[Station]: + """Return a list of stations, without duplicates when asked for.""" + return without_duplicates(stations) if self.deduplicate else stations + async def _resolve_hosts(self) -> list[str]: """Look up the Radio Browser API servers, in a random order. @@ -947,7 +1009,7 @@ async def search( # noqa: PLR0913 # yarl rejects None as a query value, so unset filters are left out. params={key: value for key, value in params.items() if value is not None}, ) - return stations_from_json(stations_data, self._corrections) + return self._station_list(stations_from_json(stations_data, self._corrections)) @probatio(error=RadioBrowserValidationError) async def station(self, *, uuid: str) -> Station | None: @@ -1077,7 +1139,7 @@ async def stations( # noqa: PLR0913 "limit": limit, }, ) - return stations_from_json(stations_data, self._corrections) + return self._station_list(stations_from_json(stations_data, self._corrections)) @probatio(error=RadioBrowserValidationError) # pylint: disable-next=too-many-arguments diff --git a/tests/test_deduplicate.py b/tests/test_deduplicate.py new file mode 100644 index 00000000..3d5c53fa --- /dev/null +++ b/tests/test_deduplicate.py @@ -0,0 +1,173 @@ +"""Tests for returning one station per stream in lists.""" + +import re +from typing import Any + +import orjson +import pytest +from aioresponses import aioresponses + +from radios import RadioBrowser, Station +from radios.radio_browser import stream_key, without_duplicates + +from .conftest import API_URL, load_fixture + +STATIONS_URL = re.compile(rf"^{re.escape(API_URL)}/stations(\?|$)") +SEARCH_URL = re.compile(rf"^{re.escape(API_URL)}/stations/search") + + +def stations_with_duplicates() -> list[dict[str, Any]]: + """Return the stations fixture, with two extra copies of the first stream.""" + stations = orjson.loads(load_fixture("stations.json")) + original = stations[0] + stations.append( + original + | { + "stationuuid": "00000000-0000-4000-8000-000000000001", + "url": original["url"].replace("http://", "https://") + "/", + "votes": original["votes"] + 1, + } + ) + stations.append( + original | {"stationuuid": "00000000-0000-4000-8000-000000000002", "votes": 0} + ) + return stations + + +@pytest.mark.parametrize( + ("first", "second"), + [ + ("http://example.com/live", "https://example.com/live"), + ("https://EXAMPLE.com/live", "https://example.com/live"), + ("https://example.com/live/", "https://example.com/live"), + ("http://example.com:8000/;", "http://example.com:8000"), + (" https://example.com/live ", "https://example.com/live"), + ], +) +def test_stream_key_same_stream(first: str, second: str) -> None: + """Test ways to write the same stream URL get the same key.""" + assert stream_key(first) == stream_key(second) + + +@pytest.mark.parametrize( + ("first", "second"), + [ + ("https://example.com/Live", "https://example.com/live"), + ("https://example.com/live?id=1", "https://example.com/live?id=2"), + ("https://example.com:8000/live", "https://example.com:8001/live"), + ], +) +def test_stream_key_other_stream(first: str, second: str) -> None: + """Test stream URLs that point to other streams get other keys.""" + assert stream_key(first) != stream_key(second) + + +def test_without_duplicates() -> None: + """Test the most voted station stays, in the place of the first copy.""" + stations = [Station.from_dict(station) for station in stations_with_duplicates()] + + unique = without_duplicates(stations) + + assert [station.uuid for station in unique] == [ + "00000000-0000-4000-8000-000000000001", + stations[1].uuid, + stations[2].uuid, + ] + + +def test_without_duplicates_ties_on_clicks() -> None: + """Test clicks decide between copies with as many votes.""" + first, second = ( + Station.from_dict(station) for station in stations_with_duplicates()[:2] + ) + first.url = second.url + first.votes = second.votes + first.click_count = second.click_count - 1 + + assert without_duplicates([first, second]) == [second] + + +def test_without_duplicates_keeps_stations_without_url() -> None: + """Test stations without a stream URL are not taken for duplicates.""" + first, second = ( + Station.from_dict(station) for station in stations_with_duplicates()[:2] + ) + first.url = second.url = "" + + assert without_duplicates([first, second]) == [first, second] + + +@pytest.mark.parametrize( + ("method", "url"), + [("stations", STATIONS_URL), ("search", SEARCH_URL)], +) +async def test_lists_without_duplicates( + responses: aioresponses, + radios: RadioBrowser, + method: str, + url: re.Pattern[str], +) -> None: + """Test lists of stations return one station per stream.""" + responses.get(url, status=200, body=orjson.dumps(stations_with_duplicates())) + + stations = await getattr(radios, method)() + + assert len(stations) == 3 + assert stations[0].uuid == "00000000-0000-4000-8000-000000000001" + + +async def test_deduplicate_can_be_turned_off( + responses: aioresponses, radios: RadioBrowser +) -> None: + """Test a client without deduplication returns every station.""" + responses.get( + STATIONS_URL, status=200, body=orjson.dumps(stations_with_duplicates()) + ) + radios.deduplicate = False + + assert len(await radios.stations()) == 5 + + +@pytest.mark.parametrize( + ("method", "arguments", "url"), + [ + ( + "stations_by_uuid", + {"uuids": ["6c95ccdb-ca0a-4c59-a660-96e56ef2dca9"]}, + re.compile(rf"^{re.escape(API_URL)}/stations/byuuid"), + ), + ( + "stations_by_url", + {"url": "https://example.com"}, + re.compile(rf"^{re.escape(API_URL)}/stations/byurl"), + ), + ], +) +async def test_lookups_keep_duplicates( + responses: aioresponses, + radios: RadioBrowser, + method: str, + arguments: dict[str, Any], + url: re.Pattern[str], +) -> None: + """Test looking stations up returns every one, so saved stations are found.""" + responses.get(url, status=200, body=orjson.dumps(stations_with_duplicates())) + + assert len(await getattr(radios, method)(**arguments)) == 5 + + +async def test_duplicates_after_corrections( + responses: aioresponses, + radios: RadioBrowser, + corrections: dict[str, dict[str, Any]], +) -> None: + """Test a corrected stream URL counts when looking for duplicates.""" + stations = orjson.loads(load_fixture("stations.json")) + corrections[stations[1]["stationuuid"]] = { + "stationuuid": stations[1]["stationuuid"], + "reason": "Moved to the stream of the first station", + "url": stations[0]["url"], + } + responses.get(STATIONS_URL, status=200, body=load_fixture("stations.json")) + + assert len(await radios.stations()) == 2