From 75771102387faf13da3597ea4787d9574503f262 Mon Sep 17 00:00:00 2001 From: Keith Smith Date: Fri, 30 Oct 2026 16:46:06 -0600 Subject: [PATCH] Add the PWA layer: manifest, service worker, icons, offline page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- apps/accounts/middleware.py | 13 +++- apps/accounts/tests.py | 7 +++ apps/pwa/tests.py | 64 ++++++++++++++++++- apps/pwa/urls.py | 11 ++++ apps/pwa/views.py | 23 ++++++- config/urls.py | 1 + static/pwa/icons/apple-touch-icon.png | Bin 0 -> 1160 bytes static/pwa/icons/icon-192.png | Bin 0 -> 1558 bytes static/pwa/icons/icon-512.png | Bin 0 -> 4820 bytes static/pwa/icons/icon-maskable.png | Bin 0 -> 3602 bytes templates/base.html | 15 +++++ templates/pwa/manifest.webmanifest | 29 +++++++++ templates/pwa/offline.html | 7 +++ templates/pwa/sw.js | 85 ++++++++++++++++++++++++++ 14 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 apps/pwa/urls.py create mode 100644 static/pwa/icons/apple-touch-icon.png create mode 100644 static/pwa/icons/icon-192.png create mode 100644 static/pwa/icons/icon-512.png create mode 100644 static/pwa/icons/icon-maskable.png create mode 100644 templates/pwa/manifest.webmanifest create mode 100644 templates/pwa/offline.html create mode 100644 templates/pwa/sw.js diff --git a/apps/accounts/middleware.py b/apps/accounts/middleware.py index f7c3feb..6cf38fa 100644 --- a/apps/accounts/middleware.py +++ b/apps/accounts/middleware.py @@ -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"), + } diff --git a/apps/accounts/tests.py b/apps/accounts/tests.py index ecb9afa..ec1b990 100644 --- a/apps/accounts/tests.py +++ b/apps/accounts/tests.py @@ -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( diff --git a/apps/pwa/tests.py b/apps/pwa/tests.py index a39b155..6c75a58 100644 --- a/apps/pwa/tests.py +++ b/apps/pwa/tests.py @@ -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 diff --git a/apps/pwa/urls.py b/apps/pwa/urls.py new file mode 100644 index 0000000..0a3a588 --- /dev/null +++ b/apps/pwa/urls.py @@ -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"), +] diff --git a/apps/pwa/views.py b/apps/pwa/views.py index 60f00ef..9f281cd 100644 --- a/apps/pwa/views.py +++ b/apps/pwa/views.py @@ -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") diff --git a/config/urls.py b/config/urls.py index 5639ef4..e68d001 100644 --- a/config/urls.py +++ b/config/urls.py @@ -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")), ] diff --git a/static/pwa/icons/apple-touch-icon.png b/static/pwa/icons/apple-touch-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..f1ae00e5624f90b9d362b552955828c413b10702 GIT binary patch literal 1160 zcmeAS@N?(olHy`uVBq!ia0vp^TR@nD4M^IaWiw)6VDa~KaSW-L^Y*T7(H#qs*1(Fa zQ;niwTjMNa;$&y?nY~E&jRyZ$_0V%)n7EPeJiK!%s9n$Rx4R;6$9ndPaE!( z3tYG5ufam~?Lj@Z9J?Ae2d>}pRiH$0(LJ{dtsTFLoAlhS$P1S^E~@jp;JWkIM>|LH zGPPG%G<9D*a{0UahV;DkUrJWz-{0?ctkUJp{C(f|9pIcO-)r^oMt#@Z3)O4?w5+~9 zefx~ZTifdvJ<81sUSxB4T5`MA!8Lon8Z0bdVYIcsE%M$(u=;dIoDSEW;*g4L|<_av2DBY`oj4&zjCH1AGf{y zYkQR5i|=cSw*M7fwC!oe|9u(u`>R%0y;^swrB3N<*!Gvfw_55JeLrHha($vx{*;pN z3r{q2o${|_C(XW+%vq%#c;5E{dr1GU6TepP;bg77u;O&h9OW02SKV_{_Y*S zz2U7}xpqyy(iz^nzssSVyv?U;astKHKxD+`G~{L>H~waBSujuBs#5)ujgOqIyELGJf+Gw{qzFSfh4b}Ag5vpVO(T3PPkGdCB>#mz61X8zXA nCFPZG`M{r6856s?{~1yqXTL6f`oR`h!Z3Kc`njxgN@xNAXnrp| literal 0 HcmV?d00001 diff --git a/static/pwa/icons/icon-192.png b/static/pwa/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..1d026edffea7cd60b794c0b403bd5a8867d38fb2 GIT binary patch literal 1558 zcmZ9Mdo+}39LJyc^_qDxllQHbamkpb*e=>hHCe(-W3aXkPTG-lri?5*GIU+Hc|*-4 znL5#gOjFq|gOIkh>(U#Er09CcPD?H25=xF-s-3of_Ut*&@A7=l@B8QHdnjN2MYHcWa-M$~}T3piea3@W+_}s|86Imw6{FiH8(FFQDmBZG=d+TB z#1+i*t3iV*eChVM#o!>j`tH4M8DMyxJ(<^d2Cz~ED_oE3A>NEKM#8U##qaU(kt{x) z8s#3=gvOeZJ-+=_L@c>kPwP;Yma`#*K&LUnKBL?YLImg_Mu;=I zRdRC~cdGo&qh>p3W#();-Z7u_s!q2@Y!I=;7ZdPQz_uiNKXwZzD?^rJH(0Pp;)4p> zRltIqAwtD-Mlhw82}%2`V7x{My!IU+kT#s)*>SKN5eSyE8x_ddBQ$19qImE1-Q2}| z0zT1j$Kibz^C;Qde#OLtOD<4SbTwfT%H*lnO39oOntB}pqVfGq*e?t1!-)g|PXSEr z)8f|{FTS-+nX8#q0c8eRZ!ts2xSVANP_6x8C+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(8`(YY)!hToNZ>4eKcEY4GqqpJY@#j|Z1~OR`p&*tA~fV|wmWw^ufU^`mW}-nDpr zVPvtUaV`&5cNVEv7+H6%7;x;4>Xo%C%fqgk1z9UnyG!>g2|DMDwfy*>nwAxg`(?WiuqXutRm>zX+mh2<$?}>%y4-LSN#&kx zrhS@GqV_w`#Ro3lomyMOVhCbvy>e3+GVLgtgE z&PeC*kZ{Djz3--{Ja3Ln+R-#-wOh=O<<5}S%y`u~x3W6qdHj+CDl-a4Jo+|7H%r0;cdxnf>EiKX zn)|ibG3&Z6b2J6N)?0{PGDhW0!9)DO>IjCdKz9mDxy>aDNst@QfZW{1H{Q9ZTQB)+|UB@S!T_pGSEx%n4%LNv~DCjb06Qblk1`ClkR+~vn{kS&{4MA@rdqkfnKjmTbIY8rLTjt0N+qzUd?!Y$yrAirCyHoIV% z>naAu4m7uoC`nF>Gi9zX$&R|>LNK=(5GLRCojF8@<}fzW{H@@`_Udh^QJ2Z&r64;O zd$noQ4)Q5=s=20apXC}0h_WB3nx6@;lDC|hOu%}Z3NgfCnF6=i&XC5qwDCY@(iQ<1 zDS$4A&w|1wht-o+~p*Rrig*8Ux|Sx zgecjGnozK#iQL_|A<*|XtTq3`LQE^@HofAQO_3OA-KGDD$oI%*E5i#ysC!TOxl4>6 z-n3?Wm#%s3Kr}^3>AXmW%}!NzhZYj8=rSX!)4`$KJEy6&Jzh%y@pfRulLc0*|4e^8 zbDf!Petg}sE)kv0ll7&ccCWg8oIzzq;jl3B(@1Yo7<$IdSWBr+EzGbs8Ojc#WE(=K zm6v{AHwS6Yp2T^T=9CDuWf^ZaUe?rajURF#&e6Gqx1-}@#-)|8sc&pv^}(#XU#D^I z4{?2x+)s{% block title %}Evection{% endblock %} + + + + + + + + {% if messages %} @@ -19,5 +27,12 @@
{% block content %}{% endblock %}
+ diff --git a/templates/pwa/manifest.webmanifest b/templates/pwa/manifest.webmanifest new file mode 100644 index 0000000..44376ea --- /dev/null +++ b/templates/pwa/manifest.webmanifest @@ -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" + } + ] +} diff --git a/templates/pwa/offline.html b/templates/pwa/offline.html new file mode 100644 index 0000000..2ee466e --- /dev/null +++ b/templates/pwa/offline.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{% block title %}Offline — Evection{% endblock %} +{% block content %} +

You're offline

+

This page isn't available offline yet. Anything you've already opened while + online should still work — try going back.

+{% endblock %} diff --git a/templates/pwa/sw.js b/templates/pwa/sw.js new file mode 100644 index 0000000..5fd79da --- /dev/null +++ b/templates/pwa/sw.js @@ -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)); + } +});