From 62eb5117f2112995a4aba0f3aaf752fa644663d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Sun, 22 Nov 2026 21:42:54 +0100 Subject: [PATCH 1/4] feat: add repository traffic analytics --- .../github_pulse/analytics/traffic.py | 137 ++++++++++++++++++ tests/analytics/test_traffic.py | 118 +++++++++++++++ 2 files changed, 255 insertions(+) create mode 100644 custom_components/github_pulse/analytics/traffic.py create mode 100644 tests/analytics/test_traffic.py diff --git a/custom_components/github_pulse/analytics/traffic.py b/custom_components/github_pulse/analytics/traffic.py new file mode 100644 index 0000000..ac20644 --- /dev/null +++ b/custom_components/github_pulse/analytics/traffic.py @@ -0,0 +1,137 @@ +"""Summaries of the GitHub traffic API (views, clones, referrers, paths). + +GitHub only reports the last 14 days. Pure and free of Home Assistant imports. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import date, datetime, timedelta +from typing import Any + +from .periods import percent_change + +TOP_LIMIT = 5 +RECENT_DAYS = 7 +WINDOW_DAYS = 14 + + +@dataclass(frozen=True, slots=True) +class TrafficTotals: + """Total and unique counts over the reported window.""" + + count: int + uniques: int + + +@dataclass(frozen=True, slots=True) +class DailyCount: + """The counts of one UTC day.""" + + day: date + count: int + uniques: int + + +@dataclass(frozen=True, slots=True) +class RankedEntry: + """One referrer or path of the popular lists.""" + + name: str + count: int + uniques: int + + +@dataclass(frozen=True, slots=True) +class RepositoryTraffic: + """The traffic of one repository over the last 14 days.""" + + views: TrafficTotals + clones: TrafficTotals + daily_views: tuple[DailyCount, ...] + referrers: tuple[RankedEntry, ...] + paths: tuple[RankedEntry, ...] + + +@dataclass(frozen=True, slots=True) +class VisitorTrend: + """Daily unique visitors of the last week against the earlier days.""" + + percent: float + recent_average: float + previous_average: float + + +def _totals(raw: dict[str, Any]) -> TrafficTotals: + return TrafficTotals(count=raw.get("count", 0), uniques=raw.get("uniques", 0)) + + +def _day(raw: dict[str, Any]) -> DailyCount: + stamp = datetime.fromisoformat(raw["timestamp"]) + return DailyCount(stamp.date(), raw["count"], raw["uniques"]) + + +def _ranked(raw: Sequence[dict[str, Any]], name_key: str) -> tuple[RankedEntry, ...]: + return tuple( + RankedEntry(item[name_key], item["count"], item["uniques"]) + for item in raw[:TOP_LIMIT] + ) + + +def parse_traffic( + views: dict[str, Any], + clones: dict[str, Any], + referrers: Sequence[dict[str, Any]], + paths: Sequence[dict[str, Any]], +) -> RepositoryTraffic: + """Turn the four traffic responses into one value. + + Missing fields count as zero, so an empty response is valid. + """ + return RepositoryTraffic( + views=_totals(views), + clones=_totals(clones), + daily_views=tuple(_day(item) for item in views.get("views", [])), + referrers=_ranked(referrers, "referrer"), + paths=_ranked(paths, "path"), + ) + + +def peak_day(traffic: RepositoryTraffic) -> DailyCount | None: + """Return the day with the most unique visitors; the latest wins a tie.""" + if not traffic.daily_views: + return None + return max(traffic.daily_views, key=lambda item: (item.uniques, item.day)) + + +def visitor_trend(traffic: RepositoryTraffic, today: date) -> VisitorTrend | None: + """Compare the daily visitor average of the last week with the days before it. + + ``today`` is incomplete and ignored. A day without an entry had no visitors. + ``None`` when the earlier days have no visitors to compare against. + """ + recent_start = today - timedelta(days=RECENT_DAYS) + window_start = today - timedelta(days=WINDOW_DAYS - 1) + recent = sum( + item.uniques for item in traffic.daily_views if recent_start <= item.day < today + ) + earlier = sum( + item.uniques + for item in traffic.daily_views + if window_start <= item.day < recent_start + ) + earlier_days = (recent_start - window_start).days + previous_average = earlier / earlier_days + recent_average = recent / RECENT_DAYS + change = percent_change(recent_average, previous_average) + if change is None: + return None + return VisitorTrend(round(change, 1), recent_average, previous_average) + + +def clone_ratio(traffic: RepositoryTraffic) -> float | None: + """Return unique cloners per unique visitor, or ``None`` without visitors.""" + if traffic.views.uniques == 0: + return None + return round(traffic.clones.uniques / traffic.views.uniques, 2) diff --git a/tests/analytics/test_traffic.py b/tests/analytics/test_traffic.py new file mode 100644 index 0000000..d1b6171 --- /dev/null +++ b/tests/analytics/test_traffic.py @@ -0,0 +1,118 @@ +"""Tests for the repository traffic summaries.""" + +from datetime import date + +from custom_components.github_pulse.analytics.traffic import ( + DailyCount, + RankedEntry, + TrafficTotals, + clone_ratio, + parse_traffic, + peak_day, + visitor_trend, +) + +TODAY = date(2026, 11, 20) + + +def _views(*days: tuple[str, int, int]) -> dict: + return { + "count": sum(count for _, count, _ in days), + "uniques": sum(uniques for _, _, uniques in days), + "views": [ + {"timestamp": f"{day}T00:00:00Z", "count": count, "uniques": uniques} + for day, count, uniques in days + ], + } + + +def _clones(count: int = 0, uniques: int = 0) -> dict: + return {"count": count, "uniques": uniques, "clones": []} + + +def _traffic(views: dict, clones: dict | None = None): + return parse_traffic(views, clones or _clones(), [], []) + + +def test_parse_reads_totals_and_top_five() -> None: + referrers = [ + {"referrer": f"site{i}", "count": 10 - i, "uniques": 5 - i} for i in range(7) + ] + paths = [ + {"path": f"/o/r/{i}", "title": "t", "count": 10 - i, "uniques": 5 - i} + for i in range(6) + ] + + traffic = parse_traffic( + _views(("2026-11-19", 4, 2)), _clones(count=9, uniques=3), referrers, paths + ) + + assert traffic.views == TrafficTotals(count=4, uniques=2) + assert traffic.clones == TrafficTotals(count=9, uniques=3) + assert traffic.daily_views == (DailyCount(date(2026, 11, 19), 4, 2),) + assert len(traffic.referrers) == 5 + assert traffic.referrers[0] == RankedEntry("site0", 10, 5) + assert len(traffic.paths) == 5 + assert traffic.paths[0] == RankedEntry("/o/r/0", 10, 5) + + +def test_parse_handles_empty_responses() -> None: + traffic = parse_traffic({}, {}, [], []) + + assert traffic.views == TrafficTotals(0, 0) + assert traffic.clones == TrafficTotals(0, 0) + assert traffic.daily_views == () + assert traffic.referrers == () + assert traffic.paths == () + + +def test_peak_day_picks_most_uniques_and_the_latest_on_a_tie() -> None: + traffic = _traffic( + _views(("2026-11-10", 9, 4), ("2026-11-12", 3, 5), ("2026-11-14", 2, 5)) + ) + + assert peak_day(traffic) == DailyCount(date(2026, 11, 14), 2, 5) + + +def test_peak_day_is_none_without_daily_data() -> None: + assert peak_day(_traffic(_views())) is None + + +def test_trend_compares_recent_week_to_earlier_days() -> None: + # Recent complete days are Nov 13-19 (7 days), earlier days Nov 7-12 (6 days). + traffic = _traffic( + _views( + ("2026-11-08", 1, 2), + ("2026-11-10", 1, 4), + ("2026-11-14", 1, 7), + ("2026-11-19", 1, 7), + ("2026-11-20", 1, 50), # today is incomplete and ignored + ) + ) + + trend = visitor_trend(traffic, TODAY) + + assert trend is not None + assert trend.recent_average == 2.0 + assert trend.previous_average == 1.0 + assert trend.percent == 100.0 + + +def test_trend_is_none_without_baseline() -> None: + only_recent = _traffic(_views(("2026-11-18", 1, 5))) + only_today = _traffic(_views(("2026-11-20", 1, 5))) + nothing = _traffic(_views()) + + assert visitor_trend(only_recent, TODAY) is None + assert visitor_trend(only_today, TODAY) is None + assert visitor_trend(nothing, TODAY) is None + + +def test_ratio_is_cloners_per_visitor() -> None: + traffic = _traffic(_views(("2026-11-19", 5, 4)), _clones(count=20, uniques=6)) + + assert clone_ratio(traffic) == 1.5 + + +def test_ratio_is_none_without_visitors() -> None: + assert clone_ratio(_traffic(_views(), _clones(count=3, uniques=2))) is None From f2687862d65f3acbee6d603a7c7d3aac56d9ec12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Sun, 22 Nov 2026 21:43:40 +0100 Subject: [PATCH 2/4] feat: fetch repository traffic as its own data group --- .../github_pulse/repository_coordinator.py | 12 +- .../github_pulse/traffic_fetch.py | 29 +++ tests/test_traffic_fetch.py | 170 ++++++++++++++++++ 3 files changed, 210 insertions(+), 1 deletion(-) create mode 100644 custom_components/github_pulse/traffic_fetch.py create mode 100644 tests/test_traffic_fetch.py diff --git a/custom_components/github_pulse/repository_coordinator.py b/custom_components/github_pulse/repository_coordinator.py index 169c913..dfcb554 100644 --- a/custom_components/github_pulse/repository_coordinator.py +++ b/custom_components/github_pulse/repository_coordinator.py @@ -9,6 +9,7 @@ from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util +from .analytics.traffic import RepositoryTraffic from .const import CONF_REPOSITORY, SUBENTRY_REPOSITORY from .coordinator import GitHubPulseCoordinator, GroupFetcher from .models import GitHubPulseConfigEntry @@ -18,10 +19,12 @@ fetch_total_downloads, ) from .settings import Settings +from .traffic_fetch import fetch_traffic GROUP_OVERVIEW = "overview" GROUP_DOWNLOADS = "downloads" -REPOSITORY_GROUPS = frozenset({GROUP_OVERVIEW, GROUP_DOWNLOADS}) +GROUP_TRAFFIC = "traffic" +REPOSITORY_GROUPS = frozenset({GROUP_OVERVIEW, GROUP_DOWNLOADS, GROUP_TRAFFIC}) def repository_subentries( @@ -61,6 +64,7 @@ def __init__( groups: dict[str, GroupFetcher] = { GROUP_OVERVIEW: self._fetch_overview, GROUP_DOWNLOADS: self._fetch_downloads, + GROUP_TRAFFIC: self._fetch_traffic, } super().__init__( hass, @@ -85,3 +89,9 @@ async def _fetch_downloads(self) -> dict[str, int]: *(fetch_total_downloads(self.client, name) for name in self.repositories) ) return dict(zip(self.repositories, totals, strict=True)) + + async def _fetch_traffic(self) -> dict[str, RepositoryTraffic | None]: + traffic = await asyncio.gather( + *(fetch_traffic(self.client, name) for name in self.repositories) + ) + return dict(zip(self.repositories, traffic, strict=True)) diff --git a/custom_components/github_pulse/traffic_fetch.py b/custom_components/github_pulse/traffic_fetch.py new file mode 100644 index 0000000..d99f42f --- /dev/null +++ b/custom_components/github_pulse/traffic_fetch.py @@ -0,0 +1,29 @@ +"""Fetch the traffic of a repository (needs push access to the repository).""" + +from __future__ import annotations + +import asyncio + +from .analytics.traffic import RepositoryTraffic, parse_traffic +from .api import GitHubClient, GitHubForbiddenError, GitHubNotFoundError + + +async def fetch_traffic( + client: GitHubClient, full_name: str +) -> RepositoryTraffic | None: + """Fetch views, clones, referrers and paths of the last 14 days. + + ``None`` when the token cannot read the traffic of this repository. Other + errors propagate. + """ + base = f"/repos/{full_name}/traffic" + try: + views, clones, referrers, paths = await asyncio.gather( + client.rest_get(f"{base}/views"), + client.rest_get(f"{base}/clones"), + client.rest_get(f"{base}/popular/referrers"), + client.rest_get(f"{base}/popular/paths"), + ) + except GitHubForbiddenError, GitHubNotFoundError: + return None + return parse_traffic(views.data, clones.data, referrers.data, paths.data) diff --git a/tests/test_traffic_fetch.py b/tests/test_traffic_fetch.py new file mode 100644 index 0000000..e610297 --- /dev/null +++ b/tests/test_traffic_fetch.py @@ -0,0 +1,170 @@ +"""Tests for the repository traffic fetch and its coordinator group.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from custom_components.github_pulse.analytics.traffic import TrafficTotals +from custom_components.github_pulse.api import ( + GitHubClient, + GitHubForbiddenError, + GitHubNotFoundError, + GitHubTransportError, +) +from custom_components.github_pulse.api.client import RestResponse +from custom_components.github_pulse.const import ( + CONF_ACTIONS, + CONF_MODULES, + CONF_OWNER, + CONF_REPOSITORY, + CONF_TOKEN_TYPE, + DOMAIN, + SUBENTRY_REPOSITORY, +) +from custom_components.github_pulse.repository_coordinator import ( + GROUP_TRAFFIC, + RepositoryCoordinator, +) +from custom_components.github_pulse.traffic_fetch import fetch_traffic +from homeassistant.config_entries import ConfigSubentryData +from homeassistant.const import CONF_ACCESS_TOKEN +from homeassistant.core import HomeAssistant +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from tests.fake_http import FakeResponse, FakeSession +from tests.test_repository_fetch import RAW + +VIEWS = { + "count": 4, + "uniques": 2, + "views": [{"timestamp": "2026-11-19T00:00:00Z", "count": 4, "uniques": 2}], +} +CLONES = {"count": 9, "uniques": 3, "clones": []} +REFERRERS = [{"referrer": "Google", "count": 4, "uniques": 2}] +PATHS = [{"path": "/a/b", "title": "a/b", "count": 4, "uniques": 2}] + +RESPONSES: dict[str, Any] = { + "/traffic/views": VIEWS, + "/traffic/clones": CLONES, + "/traffic/popular/referrers": REFERRERS, + "/traffic/popular/paths": PATHS, +} + + +def _client( + failures: dict[str, Exception] | None = None, +) -> tuple[AsyncMock, list[str]]: + """Return a client answering the traffic paths, and the paths it was asked.""" + asked: list[str] = [] + failures = failures or {} + + async def rest_get(path: str, params: Any = None) -> RestResponse: + asked.append(path) + for full_name, error in failures.items(): + if path.startswith(f"/repos/{full_name}/"): + raise error + suffix = path[path.index("/traffic") :] + return RestResponse(RESPONSES[suffix], {}) + + client = AsyncMock(spec=GitHubClient) + client.rest_get.side_effect = rest_get + client.budget = MagicMock() + client.budget.is_low.return_value = False + return client, asked + + +async def test_fetch_traffic_reads_the_four_endpoints() -> None: + client, asked = _client() + + traffic = await fetch_traffic(client, "a/b") + + assert sorted(asked) == [ + "/repos/a/b/traffic/clones", + "/repos/a/b/traffic/popular/paths", + "/repos/a/b/traffic/popular/referrers", + "/repos/a/b/traffic/views", + ] + assert traffic is not None + assert traffic.views == TrafficTotals(count=4, uniques=2) + assert traffic.clones == TrafficTotals(count=9, uniques=3) + assert traffic.referrers[0].name == "Google" + assert traffic.paths[0].name == "/a/b" + + +@pytest.mark.parametrize( + "error", [GitHubForbiddenError("no push access"), GitHubNotFoundError("hidden")] +) +async def test_an_unreadable_repository_maps_to_none(error: Exception) -> None: + client, _ = _client({"a/b": error}) + + assert await fetch_traffic(client, "a/b") is None + + +async def test_other_errors_propagate() -> None: + client, _ = _client({"a/b": GitHubTransportError("connection reset")}) + + with pytest.raises(GitHubTransportError): + await fetch_traffic(client, "a/b") + + +def _subentry(name: str) -> ConfigSubentryData: + return ConfigSubentryData( + data={CONF_REPOSITORY: name, CONF_ACTIONS: False}, + subentry_type=SUBENTRY_REPOSITORY, + title=name, + unique_id=name.lower(), + ) + + +async def _coordinator( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> RepositoryCoordinator: + patch_session( + FakeSession( + FakeResponse( + body={ + "data": { + "r0": {**RAW, "nameWithOwner": "a/one"}, + "r1": {**RAW, "nameWithOwner": "b/two"}, + } + } + ) + ) + ) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="octocat", + data={ + CONF_ACCESS_TOKEN: "token", + CONF_OWNER: "octocat", + CONF_TOKEN_TYPE: "classic", + CONF_MODULES: ["repositories"], + }, + subentries_data=[_subentry("a/one"), _subentry("b/two")], + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + return RepositoryCoordinator( + hass, + entry, + settings=entry.runtime_data.settings, + active_groups={GROUP_TRAFFIC}, + ) + + +async def test_one_forbidden_repository_keeps_the_others( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + coordinator = await _coordinator(hass, patch_session) + client, _ = _client({"b/two": GitHubForbiddenError("no push access")}) + coordinator.client = client + + await coordinator.async_refresh() + + traffic = coordinator.data[GROUP_TRAFFIC] + assert traffic["b/two"] is None + assert traffic["a/one"] is not None + assert traffic["a/one"].views.uniques == 2 From 0bcd77158507f52a8f23bcb2622097e8a298f6c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Sun, 22 Nov 2026 21:45:32 +0100 Subject: [PATCH 3/4] feat: add repository traffic sensors --- custom_components/github_pulse/sensor.py | 13 +- .../github_pulse/sensor_repository.py | 140 +++++++++++++++- .../github_pulse/translations/de.json | 27 ++++ .../github_pulse/translations/en.json | 27 ++++ tests/test_repository_sensors.py | 152 ++++++++++++++++++ 5 files changed, 354 insertions(+), 5 deletions(-) diff --git a/custom_components/github_pulse/sensor.py b/custom_components/github_pulse/sensor.py index 837bb68..54360c6 100644 --- a/custom_components/github_pulse/sensor.py +++ b/custom_components/github_pulse/sensor.py @@ -30,6 +30,7 @@ from .repository_coordinator import ( GROUP_DOWNLOADS, GROUP_OVERVIEW, + GROUP_TRAFFIC, RepositoryCoordinator, repository_subentries, ) @@ -117,7 +118,7 @@ class RepositorySensor(GitHubPulseEntity, SensorEntity): coordinator: RepositoryCoordinator entity_description: RepositorySensorDescription - _unrecorded_attributes = frozenset({"url", "name"}) + _unrecorded_attributes = frozenset({"url", "name", "referrers", "paths"}) def __init__( self, @@ -144,12 +145,18 @@ def _view(self) -> RepositoryView | None: snapshot=snapshot, total_downloads=data.get(GROUP_DOWNLOADS, {}).get(self._full_name), now=now(), + traffic=data.get(GROUP_TRAFFIC, {}).get(self._full_name), ) @property def available(self) -> bool: - """Return whether GitHub returned this repository.""" - return super().available and self._view() is not None + """Return whether GitHub returned this repository, and its traffic if read.""" + view = self._view() + if not super().available or view is None: + return False + return ( + self.entity_description.group != GROUP_TRAFFIC or view.traffic is not None + ) @property def native_value(self) -> StateType | datetime: diff --git a/custom_components/github_pulse/sensor_repository.py b/custom_components/github_pulse/sensor_repository.py index 302e4a8..9845505 100644 --- a/custom_components/github_pulse/sensor_repository.py +++ b/custom_components/github_pulse/sensor_repository.py @@ -4,7 +4,7 @@ from collections.abc import Callable, Mapping from dataclasses import dataclass -from datetime import datetime +from datetime import date, datetime from typing import Any from homeassistant.components.sensor import ( @@ -16,7 +16,15 @@ from homeassistant.util import dt as dt_util from .analytics.periods import percent_change -from .repository_coordinator import GROUP_DOWNLOADS, GROUP_OVERVIEW +from .analytics.traffic import ( + RankedEntry, + RepositoryTraffic, + VisitorTrend, + clone_ratio, + peak_day, + visitor_trend, +) +from .repository_coordinator import GROUP_DOWNLOADS, GROUP_OVERVIEW, GROUP_TRAFFIC from .repository_fetch import RepositoryActivity, RepositorySnapshot CI_STATES = ["success", "failure", "pending", "error", "expected"] @@ -31,6 +39,7 @@ class RepositoryView: snapshot: RepositorySnapshot total_downloads: int | None now: datetime + traffic: RepositoryTraffic | None = None @dataclass(frozen=True, kw_only=True) @@ -106,6 +115,132 @@ def _change_attributes(view: RepositoryView, *, year: bool) -> Attributes: } +def _ranking(entries: tuple[RankedEntry, ...]) -> list[dict[str, Any]]: + return [ + {"name": entry.name, "views": entry.count, "visitors": entry.uniques} + for entry in entries + ] + + +def _top_name(entries: tuple[RankedEntry, ...]) -> str | None: + return entries[0].name if entries else None + + +def _peak_day(view: RepositoryView) -> date | None: + peak = None if view.traffic is None else peak_day(view.traffic) + return None if peak is None else peak.day + + +def _peak_day_attributes(view: RepositoryView) -> Attributes: + peak = None if view.traffic is None else peak_day(view.traffic) + return {} if peak is None else {"visitors": peak.uniques, "views": peak.count} + + +def _trend(view: RepositoryView) -> VisitorTrend | None: + if view.traffic is None: + return None + return visitor_trend(view.traffic, view.now.date()) + + +def _trend_attributes(view: RepositoryView) -> Attributes: + trend = _trend(view) + if trend is None: + return {} + return { + "recent_daily_average": round(trend.recent_average, 2), + "previous_daily_average": round(trend.previous_average, 2), + } + + +def _traffic_description( + key: str, + value_fn: Callable[[RepositoryTraffic], Any], + **kwargs: Any, +) -> RepositorySensorDescription: + """Describe a sensor of the traffic group; all of them are off by default.""" + return RepositorySensorDescription( + key=key, + translation_key=key, + group=GROUP_TRAFFIC, + entity_registry_enabled_default=False, + value_fn=lambda view: None if view.traffic is None else value_fn(view.traffic), + **kwargs, + ) + + +TRAFFIC_SENSORS: tuple[RepositorySensorDescription, ...] = ( + _traffic_description( + "unique_visitors_14d", + lambda traffic: traffic.views.uniques, + state_class=SensorStateClass.MEASUREMENT, + ), + _traffic_description( + "views_14d", + lambda traffic: traffic.views.count, + state_class=SensorStateClass.MEASUREMENT, + ), + _traffic_description( + "unique_cloners_14d", + lambda traffic: traffic.clones.uniques, + state_class=SensorStateClass.MEASUREMENT, + ), + _traffic_description( + "clones_14d", + lambda traffic: traffic.clones.count, + state_class=SensorStateClass.MEASUREMENT, + ), + RepositorySensorDescription( + key="peak_visitor_day", + translation_key="peak_visitor_day", + group=GROUP_TRAFFIC, + entity_registry_enabled_default=False, + device_class=SensorDeviceClass.DATE, + value_fn=_peak_day, + attributes_fn=_peak_day_attributes, + ), + RepositorySensorDescription( + key="top_referrer", + translation_key="top_referrer", + group=GROUP_TRAFFIC, + entity_registry_enabled_default=False, + value_fn=lambda view: ( + None if view.traffic is None else _top_name(view.traffic.referrers) + ), + attributes_fn=lambda view: ( + {} + if view.traffic is None + else {"referrers": _ranking(view.traffic.referrers)} + ), + ), + RepositorySensorDescription( + key="top_path", + translation_key="top_path", + group=GROUP_TRAFFIC, + entity_registry_enabled_default=False, + value_fn=lambda view: ( + None if view.traffic is None else _top_name(view.traffic.paths) + ), + attributes_fn=lambda view: ( + {} if view.traffic is None else {"paths": _ranking(view.traffic.paths)} + ), + ), + RepositorySensorDescription( + key="visitor_trend", + translation_key="visitor_trend", + group=GROUP_TRAFFIC, + entity_registry_enabled_default=False, + native_unit_of_measurement=PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, + value_fn=lambda view: None if (t := _trend(view)) is None else t.percent, + attributes_fn=_trend_attributes, + ), + _traffic_description( + "clone_visitor_ratio", + clone_ratio, + state_class=SensorStateClass.MEASUREMENT, + ), +) + REPOSITORY_SENSORS: tuple[RepositorySensorDescription, ...] = ( RepositorySensorDescription( key="stars", @@ -243,6 +378,7 @@ def _change_attributes(view: RepositoryView, *, year: bool) -> Attributes: device_class=SensorDeviceClass.TIMESTAMP, value_fn=lambda view: view.snapshot.pushed_at, ), + *TRAFFIC_SENSORS, ) diff --git a/custom_components/github_pulse/translations/de.json b/custom_components/github_pulse/translations/de.json index 362eda6..2b4d502 100644 --- a/custom_components/github_pulse/translations/de.json +++ b/custom_components/github_pulse/translations/de.json @@ -193,6 +193,33 @@ "last_push": { "name": "Letzter Push" }, + "unique_visitors_14d": { + "name": "Eindeutige Besucher (14 Tage)" + }, + "views_14d": { + "name": "Seitenaufrufe (14 Tage)" + }, + "unique_cloners_14d": { + "name": "Eindeutige Cloner (14 Tage)" + }, + "clones_14d": { + "name": "Clones (14 Tage)" + }, + "peak_visitor_day": { + "name": "Spitzentag der Besucher" + }, + "top_referrer": { + "name": "Top-Referrer" + }, + "top_path": { + "name": "Top-Seite" + }, + "visitor_trend": { + "name": "Besucher-Trend" + }, + "clone_visitor_ratio": { + "name": "Cloner pro Besucher" + }, "review_requests": { "name": "Pull Requests, die auf mein Review warten" }, diff --git a/custom_components/github_pulse/translations/en.json b/custom_components/github_pulse/translations/en.json index fe9860a..e10d3fe 100644 --- a/custom_components/github_pulse/translations/en.json +++ b/custom_components/github_pulse/translations/en.json @@ -193,6 +193,33 @@ "last_push": { "name": "Last push" }, + "unique_visitors_14d": { + "name": "Unique visitors (14 days)" + }, + "views_14d": { + "name": "Page views (14 days)" + }, + "unique_cloners_14d": { + "name": "Unique cloners (14 days)" + }, + "clones_14d": { + "name": "Clones (14 days)" + }, + "peak_visitor_day": { + "name": "Peak visitor day" + }, + "top_referrer": { + "name": "Top referrer" + }, + "top_path": { + "name": "Top page" + }, + "visitor_trend": { + "name": "Visitor trend" + }, + "clone_visitor_ratio": { + "name": "Cloners per visitor" + }, "review_requests": { "name": "Pull requests awaiting my review" }, diff --git a/tests/test_repository_sensors.py b/tests/test_repository_sensors.py index 13db33f..c0da25e 100644 --- a/tests/test_repository_sensors.py +++ b/tests/test_repository_sensors.py @@ -245,3 +245,155 @@ async def test_enabling_the_downloads_sensor_fetches_that_group( assert hass.states.get(total.entity_id).state == "120" assert hass.states.get(days.entity_id).state == "1" + + +TRAFFIC_VIEWS = { + "count": 27, + "uniques": 12, + "views": [ + {"timestamp": "2026-10-14T00:00:00Z", "count": 8, "uniques": 6}, + {"timestamp": "2026-10-20T00:00:00Z", "count": 10, "uniques": 7}, + {"timestamp": "2026-10-22T00:00:00Z", "count": 9, "uniques": 7}, + ], +} +TRAFFIC_CLONES = {"count": 30, "uniques": 6, "clones": []} +TRAFFIC_REFERRERS = [ + {"referrer": "Google", "count": 20, "uniques": 9}, + {"referrer": "github.com", "count": 7, "uniques": 3}, +] +TRAFFIC_PATHS = [ + {"path": "/Octocat/Hello-World", "title": "Hello", "count": 22, "uniques": 10} +] +TRAFFIC_KEYS = ( + "unique_visitors_14d", + "views_14d", + "unique_cloners_14d", + "clones_14d", + "peak_visitor_day", + "top_referrer", + "top_path", + "visitor_trend", + "clone_visitor_ratio", +) + + +class _TrafficSession(_Session): + """Also answer the traffic endpoints, or refuse them, and record the paths.""" + + def __init__(self, *, forbidden: bool = False) -> None: + super().__init__() + self.traffic_urls: list[str] = [] + self._forbidden = forbidden + + def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse: + if "/traffic/" not in url: + return super().request(method, url, **kwargs) + self.traffic_urls.append(url) + if self._forbidden: + return FakeResponse( + status=403, body={"message": "Resource not accessible by integration"} + ) + bodies = { + "/traffic/views": TRAFFIC_VIEWS, + "/traffic/clones": TRAFFIC_CLONES, + "/traffic/popular/referrers": TRAFFIC_REFERRERS, + "/traffic/popular/paths": TRAFFIC_PATHS, + } + return FakeResponse(body=next(b for p, b in bodies.items() if p in url)) + + +async def _setup_traffic( + hass: HomeAssistant, + patch_session: Callable[[FakeSession], None], + session: _TrafficSession, + *, + enable: tuple[str, ...], +) -> MockConfigEntry: + patch_session(session) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="octocat", + data={ + CONF_ACCESS_TOKEN: "token", + CONF_OWNER: "octocat", + CONF_TOKEN_TYPE: "classic", + CONF_MODULES: ["repositories"], + }, + subentries_data=[ + ConfigSubentryData( + data={CONF_REPOSITORY: "Octocat/Hello-World", CONF_ACTIONS: False}, + subentry_type=SUBENTRY_REPOSITORY, + title="Octocat/Hello-World", + unique_id="octocat/hello-world", + ) + ], + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + if enable: + registry = er.async_get(hass) + for key in enable: + entity = next( + e + for e in registry.entities.values() + if e.unique_id.endswith(f"hello-world_{key}") + ) + registry.async_update_entity(entity.entity_id, disabled_by=None) + await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + return entry + + +async def test_the_traffic_group_is_not_fetched_while_every_traffic_sensor_is_off( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + session = _TrafficSession() + + await _setup_traffic(hass, patch_session, session, enable=()) + + assert session.traffic_urls == [] + + +async def test_enabling_traffic_sensors_reports_the_traffic( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + session = _TrafficSession() + await _setup_traffic(hass, patch_session, session, enable=TRAFFIC_KEYS) + repo = "Octocat/Hello-World" + + assert _state(hass, repo, "unique_visitors_14d").state == "12" + assert _state(hass, repo, "views_14d").state == "27" + assert _state(hass, repo, "unique_cloners_14d").state == "6" + assert _state(hass, repo, "clones_14d").state == "30" + peak = _state(hass, repo, "peak_visitor_day") + assert peak.state == "2026-10-22" + assert peak.attributes["visitors"] == 7 + assert peak.attributes["views"] == 9 + referrer = _state(hass, repo, "top_referrer") + assert referrer.state == "Google" + assert referrer.attributes["referrers"][0] == { + "name": "Google", + "views": 20, + "visitors": 9, + } + assert len(referrer.attributes["referrers"]) == 2 + path = _state(hass, repo, "top_path") + assert path.state == "/Octocat/Hello-World" + assert path.attributes["paths"][0]["visitors"] == 10 + trend = _state(hass, repo, "visitor_trend") + assert trend.state == "100.0" + assert trend.attributes["recent_daily_average"] == 2.0 + assert trend.attributes["previous_daily_average"] == 1.0 + assert _state(hass, repo, "clone_visitor_ratio").state == "0.5" + + +async def test_traffic_sensors_are_unavailable_without_push_access( + hass: HomeAssistant, patch_session: Callable[[FakeSession], None] +) -> None: + session = _TrafficSession(forbidden=True) + await _setup_traffic(hass, patch_session, session, enable=TRAFFIC_KEYS) + + for key in TRAFFIC_KEYS: + assert _state(hass, "Octocat/Hello-World", key).state == "unavailable", key + assert _state(hass, "Octocat/Hello-World", "stars").state == "42" From 95da8bfda5dc9ee786fa8715ef092d84e2fab1d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Sun, 22 Nov 2026 21:46:10 +0100 Subject: [PATCH 4/4] docs: document repository traffic sensors --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 131e4d8..645b9a9 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,9 @@ The setup checks the token against every module you select and tells you what is > [!IMPORTANT] > Fine-grained tokens belong to a single owner and cannot read Packages. Use a classic token if you need more. +> [!NOTE] +> The repository traffic sensors only work for repositories you have write access to; GitHub shows traffic to no one else, and only for the last 14 days. A classic token with `repo` covers it. GitHub does not document a fine-grained permission for traffic, so if the sensors stay unavailable with a fine-grained token, use a classic one. + --- ## ๐Ÿงฉ What you get @@ -87,7 +90,7 @@ The setup checks the token against every module you select and tells you what is | โš™๏ธ | Workflow runs | Per repository, if you turn on **Track workflow runs**: last result, runs today, queued runs, failure rate over 7 and 30 days, average duration, and a binary sensor while a workflow runs | | ๐Ÿ”” | Events | Event entities per repository (workflow failed or recovered, release published) and for your account (review requested, pull request merged), also fired on the event bus | | ๐Ÿงช | Custom queries | Your own read-only GraphQL query as a sensor, added under **Add custom query**. Rendered with templates over `value_json`. Presets included; see the [guide](docs/custom-queries.md) | -| โž• | Optional sensors | Reviews, issues, active days, strongest weekday, watchers, release downloads, days since last commit or release, pull requests awaiting your review, most active hour and night-owl score (approximate, from GitHub's last 300 events), average time to merge (last 50 merged pull requests), stale pull requests (open, untouched for 14 days), year in review (one-line summary with the details as attributes), followers and following counts | +| โž• | Optional sensors | Reviews, issues, active days, strongest weekday, watchers, release downloads, days since last commit or release, pull requests awaiting your review, most active hour and night-owl score (approximate, from GitHub's last 300 events), average time to merge (last 50 merged pull requests), stale pull requests (open, untouched for 14 days), year in review (one-line summary with the details as attributes), followers and following counts, repository traffic (unique visitors and cloners and page views and clones over the last 14 days, peak visitor day, top referrer and page, visitor trend, cloners per visitor; needs write access, see [Access token](#-access-token)) | Everything marked optional is created disabled. GitHub Pulse only fetches data that an enabled entity needs, so unused sensors cost no API calls.