-
-
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
Open
mrdarrengriffin
wants to merge
6
commits into
hacs:main
Choose a base branch
from
mrdarrengriffin:claude/plausible-analytics-setup-eu5vam
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 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 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,3 @@ | ||
| mkdocs-material[imaging]==9.7.5 | ||
| mkdocs-macros-plugin==1.5.0 | ||
| requests==2.34.2 |
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,75 @@ | ||
| 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("Discarding unusable allow list at %s: %s", ALLOWLIST_FILE, exception) | ||
| 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") | ||
| log.info("Fetched %s allowed referrers", len(referrers)) | ||
| return referrers | ||
|
|
||
|
|
||
| def allowed_referrers() -> list[str]: | ||
| """The allow list, downloaded at most once per build. | ||
|
|
||
| An empty result means no referrer can be checked, which leaves Plausible out of | ||
| the build entirely rather than reporting every visit as unlisted. | ||
| """ | ||
| 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("Could not refresh the allow list, reusing %s: %s", ALLOWLIST_FILE, exception) | ||
| return cached | ||
| log.info("Could not fetch the allow list (%s), Plausible is left out of this build", exception) | ||
| 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,12 @@ | ||
| {% 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") | ||
| }; | ||
| }); | ||
| </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,62 @@ | ||
| {#- | ||
| 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. | ||
|
|
||
| If the allow list could not be fetched there is nothing to check referrers | ||
| against, so analytics stays off for that build rather than reporting every visit | ||
| as unlisted. | ||
| -#} | ||
| {%- if config.extra.plausible.allowed_referrers %} | ||
| <script async src="{{ config.extra.plausible.script }}"></script> | ||
| <script> | ||
| (function () { | ||
| var allowedReferrers = {{ config.extra.plausible.allowed_referrers | tojson }}; | ||
|
|
||
| // 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. | ||
| function unlisted(payload) { | ||
| payload.r = "https://unlisted.invalid/"; | ||
| return payload; | ||
| } | ||
|
|
||
| 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 { | ||
| // The URL parser only lowercases the host of special schemes, so | ||
| // android-app:// and other referrers still need folding. | ||
| host = new URL(payload.r).hostname.toLowerCase().replace(/\.$/, ""); | ||
| } catch (error) { | ||
| return unlisted(payload); | ||
| } | ||
|
|
||
| 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.
|
||
|
|
||
| return unlisted(payload); | ||
| }, | ||
| }); | ||
| })(); | ||
| </script> | ||
| {%- endif %} | ||
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.