Add the PWA layer: manifest, service worker, icons, offline page

Implements installable-PWA support per the plan: a manifest.webmanifest
view (name/short_name "Evection", standalone display, 192/512/maskable
icons), a service worker served at domain root (/sw.js, with
Service-Worker-Allowed: / so its scope covers the whole app, not just
/static/), and an offline fallback page.

The service worker ignores all non-GET requests outright (so mutations
like mark-read/star/OPML upload stay network-only without special-
casing every endpoint), does network-first-with-cache-fallback for
navigations (bounded to the 60 most recently viewed pages, trimmed
oldest-first), and cache-first for /static/ assets, with the cache
name keyed by EVECTION_PWA_CACHE_VERSION so a deploy can invalidate
old caches. Per the earlier decision, embedded remote images in
article content are not cached for offline reading — text/HTML only.

Generates a simple RSS-glyph icon set (192/512/maskable/apple-touch)
with a throwaway Pillow script (not a project dependency). Adds iOS
meta tags and service-worker registration to base.html. Fixed a real
bug found during this work: the first-run setup-wizard middleware was
redirecting /manifest.webmanifest, /sw.js, and /offline/ to /setup/
before an admin account existed, which would have broken a browser's
very first visit to a fresh install.

Verified: manifest JSON validity and required fields, sw.js delivery
(content-type, Service-Worker-Allowed header, correct body) via both
curl and automated tests (112 passing). Actual service-worker
registration could not be verified in this sandboxed browser pane —
confirmed via a control test (even a trivial unrelated static file
fails to register here with an opaque "unknown error fetching script")
that this is an environment limitation of locally-started dev servers
in this tool, not an application bug; registration, install-prompt,
and offline behavior need confirming in a real browser.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-30 16:46:06 -06:00
1 parent ea214dd9ce
commit 7577110238
14 files changed
+252 -3

No files matched your search

+12 -1
View File
@@ -24,10 +24,21 @@ class SetupWizardMiddleware:
def __call__(self, request):
path = request.path
if not path.startswith(_SETUP_EXEMPT_PREFIXES):
if not path.startswith(_SETUP_EXEMPT_PREFIXES) and path not in _pwa_exempt_paths():
if not SetupWizardMiddleware._a_user_exists:
SetupWizardMiddleware._a_user_exists = User.objects.exists()
setup_url = reverse("accounts:setup")
if path != setup_url and not SetupWizardMiddleware._a_user_exists:
return redirect(setup_url)
return self.get_response(request)
def _pwa_exempt_paths():
"""The manifest/service worker/offline page must work even before the
instance's first-run setup is complete — a browser can fetch these on
any visit, setup page included (it extends the same base template)."""
return {
reverse("pwa:manifest"),
reverse("pwa:service_worker"),
reverse("pwa:offline"),
}
+7
View File
@@ -19,6 +19,13 @@ def test_root_redirects_to_setup_when_no_users_exist(client):
assert response.url == reverse("accounts:setup")
@pytest.mark.django_db
def test_pwa_routes_bypass_the_setup_redirect(client):
for url_name in ["pwa:manifest", "pwa:service_worker", "pwa:offline"]:
response = client.get(reverse(url_name))
assert response.status_code == 200, url_name
@pytest.mark.django_db
def test_setup_creates_admin_and_logs_in(client):
response = client.post(
+63 -1
View File
@@ -1 +1,63 @@
# Create your tests here.
import json
import pytest
from django.urls import reverse
@pytest.mark.django_db
def test_manifest_is_valid_json_with_expected_fields(client):
response = client.get(reverse("pwa:manifest"))
assert response.status_code == 200
assert response["Content-Type"] == "application/manifest+json"
manifest = json.loads(response.content)
assert manifest["name"] == "Evection"
assert manifest["display"] == "standalone"
assert manifest["scope"] == "/"
sizes = {icon["sizes"] for icon in manifest["icons"]}
assert {"192x192", "512x512"} <= sizes
assert any(icon.get("purpose") == "maskable" for icon in manifest["icons"])
@pytest.mark.django_db
def test_service_worker_is_served_at_root_with_correct_type_and_scope(client):
response = client.get(reverse("pwa:service_worker"))
assert response.status_code == 200
assert response["Content-Type"] == "application/javascript"
assert response["Service-Worker-Allowed"] == "/"
body = response.content.decode()
assert 'self.addEventListener("install"' in body
assert 'self.addEventListener("fetch"' in body
# Mutations must stay network-only, never intercepted.
assert 'request.method !== "GET"' in body
@pytest.mark.django_db
def test_offline_page_renders(client):
response = client.get(reverse("pwa:offline"))
assert response.status_code == 200
assert b"offline" in response.content.lower()
@pytest.mark.django_db
def test_manifest_and_sw_do_not_require_login(client):
# The service worker fetches these itself, unauthenticated, before any
# user necessarily has a session.
assert client.get(reverse("pwa:manifest")).status_code == 200
assert client.get(reverse("pwa:service_worker")).status_code == 200
assert client.get(reverse("pwa:offline")).status_code == 200
@pytest.mark.django_db
def test_base_template_links_manifest_and_registers_service_worker(client, django_user_model):
django_user_model.objects.create_user("alice", password="pw-alice-123")
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"))
content = response.content.decode()
assert 'rel="manifest"' in content
assert "serviceWorker" in content
assert "apple-touch-icon" in content
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from . import views
app_name = "pwa"
urlpatterns = [
path("manifest.webmanifest", views.manifest, name="manifest"),
path("sw.js", views.service_worker, name="service_worker"),
path("offline/", views.offline, name="offline"),
]
+22 -1
View File
@@ -1 +1,22 @@
# Create your views here.
from django.conf import settings
from django.shortcuts import render
def manifest(request):
return render(request, "pwa/manifest.webmanifest", content_type="application/manifest+json")
def service_worker(request):
context = {"cache_version": settings.EVECTION_PWA_CACHE_VERSION}
response = render(request, "pwa/sw.js", context, content_type="application/javascript")
# A service worker's own scope covers everything below where it's
# served from, but the browser also independently refuses a broader
# Service-Worker-Allowed scope than the response's own URL path
# implies unless this header says otherwise. Being served at exactly
# "/sw.js" already gives it root scope, so this is just explicit.
response["Service-Worker-Allowed"] = "/"
return response
def offline(request):
return render(request, "pwa/offline.html")
+1
View File
@@ -8,5 +8,6 @@ urlpatterns = [
path("", include("apps.articles.urls")),
path("", include("apps.rules.urls")),
path("", include("apps.search.urls")),
path("", include("apps.pwa.urls")),
path("", include("apps.reader.urls")),
]
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

+15
View File
@@ -7,6 +7,14 @@
<title>{% block title %}Evection{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
<script src="{% static 'js/htmx.min.js' %}" defer></script>
<link rel="manifest" href="{% url 'pwa:manifest' %}">
<meta name="theme-color" content="#111111">
<link rel="icon" href="{% static 'pwa/icons/icon-192.png' %}">
<link rel="apple-touch-icon" href="{% static 'pwa/icons/apple-touch-icon.png' %}">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Evection">
</head>
<body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
{% if messages %}
@@ -19,5 +27,12 @@
<main>
{% block content %}{% endblock %}
</main>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("{% url 'pwa:service_worker' %}");
});
}
</script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
{% load static %}{
"name": "Evection",
"short_name": "Evection",
"description": "A self-hosted RSS/Atom feed reader.",
"start_url": "{% url 'reader:stream' %}",
"scope": "/",
"display": "standalone",
"background_color": "#111111",
"theme_color": "#111111",
"orientation": "portrait-primary",
"icons": [
{
"src": "{% static 'pwa/icons/icon-192.png' %}",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "{% static 'pwa/icons/icon-512.png' %}",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "{% static 'pwa/icons/icon-maskable.png' %}",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
+7
View File
@@ -0,0 +1,7 @@
{% extends "base.html" %}
{% block title %}Offline — Evection{% endblock %}
{% block content %}
<h1>You're offline</h1>
<p>This page isn't available offline yet. Anything you've already opened while
online should still work — try going back.</p>
{% endblock %}
+85
View File
@@ -0,0 +1,85 @@
{% load static %}const CACHE_VERSION = "{{ cache_version }}";
const SHELL_CACHE = `evection-shell-${CACHE_VERSION}`;
const PAGES_CACHE = `evection-pages-${CACHE_VERSION}`;
const MAX_CACHED_PAGES = 60;
const SHELL_URLS = [
"{% url 'pwa:offline' %}",
"{% url 'accounts:login' %}",
"{% static 'css/base.css' %}",
"{% static 'js/htmx.min.js' %}",
"{% static 'pwa/icons/icon-192.png' %}",
"{% static 'pwa/icons/icon-512.png' %}",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL_URLS)).then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names
.filter((name) => name !== SHELL_CACHE && name !== PAGES_CACHE)
.map((name) => caches.delete(name))
)
)
.then(() => self.clients.claim())
);
});
async function trimCache(cacheName, maxItems) {
const cache = await caches.open(cacheName);
const keys = await cache.keys();
if (keys.length <= maxItems) return;
// Cache.keys() returns insertion order, so the oldest entries are first.
const toDelete = keys.slice(0, keys.length - maxItems);
await Promise.all(toDelete.map((key) => cache.delete(key)));
}
async function networkFirstForNavigation(request) {
try {
const response = await fetch(request);
const cache = await caches.open(PAGES_CACHE);
cache.put(request, response.clone());
trimCache(PAGES_CACHE, MAX_CACHED_PAGES);
return response;
} catch (err) {
const cached = await caches.match(request);
if (cached) return cached;
const offline = await caches.match("{% url 'pwa:offline' %}");
return offline || Response.error();
}
}
async function cacheFirstForAsset(request) {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
const cache = await caches.open(SHELL_CACHE);
cache.put(request, response.clone());
return response;
}
self.addEventListener("fetch", (event) => {
const { request } = event;
// Mutations (mark-read, star, OPML upload, forms...) are always
// network-only — never intercept anything but GET.
if (request.method !== "GET") return;
if (request.mode === "navigate") {
event.respondWith(networkFirstForNavigation(request));
return;
}
const url = new URL(request.url);
if (url.pathname.startsWith("/static/")) {
event.respondWith(cacheFirstForAsset(request));
}
});