-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Reimplement Plausible analytics #704
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ludeeus
merged 7 commits into
hacs:main
from
mrdarrengriffin:claude/plausible-analytics-setup-eu5vam
Aug 19, 2026
Merged
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c209d4f
Reimplement Plausible analytics
claude 908d47d
Merge branch 'main' into claude/plausible-analytics-setup-eu5vam
mrdarrengriffin e3ef6e8
Declare requests and restore the updated Plausible script src
claude c699b42
Update source/overrides/404.html
mrdarrengriffin 6655f95
Update source/hooks/plausible.py
mrdarrengriffin cdec767
Address review: early return, host folding, and no-allow-list behaviour
claude 6b8e509
Re-trigger CI
mrdarrengriffin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import logging | ||
| import time | ||
| from pathlib import Path | ||
|
|
||
| import requests | ||
| from mkdocs.config.defaults import MkDocsConfig | ||
|
|
||
| ALLOWLIST_URL = "https://www.openhomefoundation.org/allowed-referrers.json" | ||
| ALLOWLIST_FILE = Path(".cache/plausible/allowed-referrers.json") | ||
| ALLOWLIST_MAX_AGE = 3600 | ||
|
|
||
| # `strict: true` aborts the build on anything logged at WARNING or above under the | ||
| # "mkdocs" logger, and an unreachable allow list must never break the site, so the | ||
| # fallbacks below report at INFO instead. | ||
| log = logging.getLogger("mkdocs.hooks.plausible") | ||
|
|
||
|
|
||
| def normalize_referrers(payload: object) -> list[str]: | ||
| """Reduce the allow list payload to bare, lowercase domains.""" | ||
| if not isinstance(payload, list) or not all(isinstance(entry, str) for entry in payload): | ||
| raise ValueError("payload is not an array of strings") | ||
| return [domain for entry in payload if (domain := entry.strip().lower().removesuffix("."))] | ||
|
|
||
|
|
||
| def cached_referrers() -> list[str] | None: | ||
| """The allow list left behind by an earlier build, if it is still usable.""" | ||
| try: | ||
| return normalize_referrers(json.loads(ALLOWLIST_FILE.read_text())) | ||
| except FileNotFoundError: | ||
| return None | ||
| except (OSError, ValueError) as exception: | ||
| log.info(f"Discarding unusable allow list at {ALLOWLIST_FILE}: {exception}") | ||
|
mrdarrengriffin marked this conversation as resolved.
Outdated
|
||
| return None | ||
|
|
||
|
|
||
| def download_referrers() -> list[str]: | ||
| """Download the allow list and cache it for subsequent builds.""" | ||
| response = requests.get(ALLOWLIST_URL, timeout=30) | ||
| response.raise_for_status() | ||
| referrers = normalize_referrers(response.json()) | ||
| ALLOWLIST_FILE.parent.mkdir(parents=True, exist_ok=True) | ||
| ALLOWLIST_FILE.write_text(json.dumps(referrers, indent=4, sort_keys=True) + "\n") | ||
|
mrdarrengriffin marked this conversation as resolved.
|
||
| log.info(f"Fetched {len(referrers)} allowed referrers") | ||
| return referrers | ||
|
|
||
|
|
||
| def allowed_referrers() -> list[str]: | ||
| """The allow list, downloaded at most once per build.""" | ||
| if ( | ||
| ALLOWLIST_FILE.exists() | ||
| and time.time() - ALLOWLIST_FILE.stat().st_mtime < ALLOWLIST_MAX_AGE | ||
| and (cached := cached_referrers()) is not None | ||
| ): | ||
| return cached | ||
|
|
||
| try: | ||
| return download_referrers() | ||
| except (OSError, ValueError, requests.RequestException) as exception: | ||
| if (cached := cached_referrers()) is not None: | ||
| log.info(f"Could not refresh the allow list, reusing {ALLOWLIST_FILE}: {exception}") | ||
| return cached | ||
| log.info( | ||
| f"Could not fetch the allow list ({exception}), " | ||
| "every referrer will be reported to Plausible as unlisted" | ||
|
mrdarrengriffin marked this conversation as resolved.
Outdated
|
||
| ) | ||
| return [] | ||
|
|
||
|
|
||
| def on_config(config: MkDocsConfig, **kwargs): | ||
| config.extra.setdefault("plausible", {})["allowed_referrers"] = allowed_referrers() | ||
| return config | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,10 @@ | ||
| {% extends "main.html" %} | ||
|
|
||
| {% block content %} | ||
| <h1>404 - Not found</h1> | ||
| <script>document.addEventListener("DOMContentLoaded", function () { plausible("404"); });</script> | ||
| {% endblock %} | ||
| {% extends "main.html" %} | ||
|
|
||
| {% block content %} | ||
| <h1>404 - Not found</h1> | ||
| <script> | ||
| document.addEventListener("DOMContentLoaded", function () { | ||
| if (typeof window.plausible === "function") window.plausible("404"); | ||
|
mrdarrengriffin marked this conversation as resolved.
Outdated
|
||
| }); | ||
| </script> | ||
| {% endblock %} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,5 @@ | ||
| <footer class="md-footer md-typeset"> | ||
| <p class="plausible-attribution"> | ||
| This website uses <a href="https://www.openhomefoundation.org/blog/making-our-web-analytics-open-source-with-plausible/" target="_blank" rel="noopener">privacy-first analytics</a> to help us improve the site. You can view all data in our <a href="https://plausible.openhomefoundation.org/hacs.xyz" target="_blank" rel="noopener">public dashboard</a>. | ||
| This website uses <a href="https://www.openhomefoundation.org/blog/making-our-web-analytics-open-source-with-plausible/" target="_blank" rel="noopener">privacy-first analytics</a> to help us improve the site. You can view all data in our <a href="{{ config.extra.plausible.dashboard }}" target="_blank" rel="noopener">public dashboard</a>. | ||
| </p> | ||
| </footer> | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| {#- | ||
| Plausible analytics. | ||
|
|
||
| Visitors arriving from their own Home Assistant or ESPHome instance send that | ||
|
mrdarrengriffin marked this conversation as resolved.
|
||
| private URL as the referrer, so the tracker is initialized with a transformRequest | ||
| that replaces every referrer outside the Open Home Foundation allow list with a | ||
| single aggregate bucket. source/hooks/plausible.py fetches the allow list once per | ||
| build and the loop below is the only thing that ever sees the real referrer. | ||
| -#} | ||
| <script async src="{{ config.extra.plausible.script }}"></script> | ||
|
ludeeus marked this conversation as resolved.
|
||
| <script> | ||
| (function () { | ||
| var allowedReferrers = {{ config.extra.plausible.allowed_referrers | tojson }}; | ||
|
|
||
| window.plausible = window.plausible || function () { | ||
| (plausible.q = plausible.q || []).push(arguments); | ||
| }; | ||
| plausible.init = plausible.init || function (options) { | ||
| plausible.o = options || {}; | ||
| }; | ||
|
|
||
| plausible.init({ | ||
| transformRequest: function (payload) { | ||
| if (!payload.r) { | ||
| return payload; | ||
| } | ||
|
|
||
| var host = ""; | ||
| try { | ||
| host = new URL(payload.r).hostname.replace(/\.$/, ""); | ||
|
mrdarrengriffin marked this conversation as resolved.
Outdated
|
||
| } catch (error) { | ||
| // A referrer we cannot parse falls through and gets replaced. | ||
|
mrdarrengriffin marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| for (var index = 0; index < allowedReferrers.length; index++) { | ||
| var domain = allowedReferrers[index]; | ||
| if (host === domain || (host.length > domain.length && host.slice(-(domain.length + 1)) === "." + domain)) { | ||
| return payload; | ||
| } | ||
| } | ||
|
mrdarrengriffin marked this conversation as resolved.
|
||
|
|
||
| // One aggregate bucket, so we can see how much we filter without learning | ||
| // anything about individual visitors. RFC 2606 reserves .invalid, so this | ||
| // can never collide with a real domain. | ||
| payload.r = "https://unlisted.invalid/"; | ||
| return payload; | ||
| }, | ||
| }); | ||
| })(); | ||
| </script> | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.