Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
137 changes: 137 additions & 0 deletions custom_components/github_pulse/analytics/traffic.py
Original file line number Diff line number Diff line change
@@ -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)
12 changes: 11 additions & 1 deletion custom_components/github_pulse/repository_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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))
13 changes: 10 additions & 3 deletions custom_components/github_pulse/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from .repository_coordinator import (
GROUP_DOWNLOADS,
GROUP_OVERVIEW,
GROUP_TRAFFIC,
RepositoryCoordinator,
repository_subentries,
)
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down
Loading
Loading