latest changes
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
.venv/
|
||||
.venv-host/
|
||||
node_modules/
|
||||
dist/
|
||||
*.pyc
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Dashboard widget contract
|
||||
|
||||
- Render every widget inside the shared minimal base card using existing CSS tokens. Keep widget data and business logic outside the card.
|
||||
- Register widgets with a stable type ID and validated title, description, icon, template, span, settings keys, permissions, and multi-instance policy.
|
||||
- The dashboard layout engine alone owns add, drag, drop, order, size, and per-user, per-page persistence. Widget scripts must initialize and clean up within their own root, including after partial page updates.
|
||||
- Provide keyboard and touch alternatives to dragging, clear focus, screen-reader status, reduced motion, and WCAG 2.2 AA interaction and contrast.
|
||||
- Show loading, empty, error, and stale states honestly. Show visible provider attribution when required.
|
||||
- Require Django authentication and CSRF for layout changes. Validate configuration on the server, enforce ownership, and keep upstream secrets out of browser code.
|
||||
- Test registry validation, user and page isolation, reorder persistence, and widget lifecycle when adding widgets.
|
||||
- The card's `data-widget-platform` and `data-instance-id` are passive geometry hooks for future integrations. Do not add companion behavior here.
|
||||
@@ -14,7 +14,25 @@ npm run dev
|
||||
|
||||
The dashboard runs at `http://127.0.0.1:8765/`. `npm run dev` uses the existing package scripts; `npm run dev:mcp` starts the MCP process at `http://127.0.0.1:8766/mcp`. If Node.js is unavailable, use `.venv/bin/uvicorn mcp_server.server:app --host 127.0.0.1 --port 8766`. Port 8766 is separate from TasksNest's MCP listener.
|
||||
|
||||
`/projects/` contains active and archived projects. New projects seed editable To-do, In Progress, and Done columns. New cards use the board's selected default column and Medium priority. Cards store raw Markdown, a revision history, explicit blockers, comments, and activity. HTML output is sanitized. Git URLs are metadata; the server does not fetch or clone them.
|
||||
### Persistent local services
|
||||
|
||||
This host runs systemd with Python 3.12, while the development shell's `.venv` uses Python 3.13. The user services in `deploy/systemd/` therefore use the project-local `.venv-host`. To recreate it on the host, run `python3 -m venv .venv-host` and `.venv-host/bin/python -m pip install -r requirements.txt` there. Keep both virtualenvs out of Git.
|
||||
|
||||
The linked `common-ground-django.service` and `common-ground-mcp.service` start on login or boot through the systemd user manager. The local Django service binds to `127.0.0.1:8765`; MCP binds only to the host's Tailscale address, `100.91.62.59:8766`. Manage them with:
|
||||
|
||||
```sh
|
||||
systemctl --user status common-ground-django.service common-ground-mcp.service
|
||||
systemctl --user restart common-ground-django.service common-ground-mcp.service
|
||||
journalctl --user -u common-ground-mcp.service -f
|
||||
```
|
||||
|
||||
The Django process on port 8765 provides a local dashboard and OAuth server. The public Caddy configuration currently forwards the dashboard and OAuth routes to a separate Django process at `100.91.62.59:2345`, and MCP routes to `100.91.62.59:8766`. An unauthenticated `GET /mcp` should return HTTP 401. Optional settings for the user services belong in `~/.config/common-ground/env`, outside the repository. After changing that file, restart the affected service.
|
||||
|
||||
Remote clients use the public HTTPS reverse proxy. Route `/mcp` and `/.well-known/oauth-protected-resource/mcp` to the Tailscale-only MCP listener on port 8766, and the dashboard plus OAuth discovery and `/o/` to the Django process on port 2345. The processes must share the same database and `DJANGO_SECRET_KEY`. Keep MCP off public and LAN interfaces; the Tailscale address is reachable through the authenticated tailnet.
|
||||
|
||||
For `https://projects.jorendegraaf.eu`, MCP advertises `MCP_PUBLIC_URL=https://projects.jorendegraaf.eu/mcp` and `OAUTH_ISSUER_URL=https://projects.jorendegraaf.eu`. Set these in the public Django process too, especially to make its Profile configuration check agree. Profile shows the visiting HTTPS origin plus `/mcp`; on localhost it retains the separate development port. OAuth discovery, protected-resource metadata, and the reverse proxy must agree on the public URLs before a remote client can connect. Redirect the singular `project.jorendegraaf.eu` alias to the canonical plural hostname so OAuth resource identifiers remain consistent. Keep `DJANGO_ALLOWED_HOSTS` restricted to served hostnames. Caddy forwards the original `Host` and `X-Forwarded-Proto` headers by default.
|
||||
|
||||
`/projects/` contains active and archived projects. New projects seed editable To-do, In Progress, and Done columns. New cards use the board's selected default column and Medium priority. Cards store raw Markdown, a revision history, explicit blockers, comments, and activity. HTML output is sanitized. Git URLs are metadata; the server does not fetch or clone them. Profile timezone accepts an IANA name and controls timestamps on authenticated pages; the default is Europe/Amsterdam.
|
||||
|
||||
## OAuth and MCP
|
||||
|
||||
@@ -22,6 +40,8 @@ The Django server hosts OAuth authorization, token, revocation, and discovery en
|
||||
|
||||
Authenticated dynamic client registration is enabled at `/o/register/`. A signed-in user can register a client; session requests also need a CSRF token. Anonymous registration is denied. You can also create a public authorization-code client in Django admin, setting its exact HTTPS redirect URI and the needed scopes. Profile shows active grants and revocation controls.
|
||||
|
||||
For ChatGPT's custom MCP plugin, open Advanced OAuth settings and choose a provided/registered client rather than dynamic registration. Use the public authorization-code client registered with redirect URI `https://chatgpt.com/connector_platform_oauth_redirect`, token endpoint authentication method `none`, and default scope `projects:read` (add `projects:write` to enable edits). The server URL is `https://projects.jorendegraaf.eu/mcp`; the authorization and token endpoints are `https://projects.jorendegraaf.eu/o/authorize/` and `https://projects.jorendegraaf.eu/o/token/`. The protected-resource metadata's authorization server must exactly match the OAuth discovery issuer, including its trailing slash.
|
||||
|
||||
Local accounts work by default. To enable separate OIDC sign-in to the dashboard, set `OIDC_OP_ISSUER`, `OIDC_OP_AUTHORIZATION_ENDPOINT`, `OIDC_OP_TOKEN_ENDPOINT`, `OIDC_OP_USER_ENDPOINT`, `OIDC_OP_JWKS_ENDPOINT`, `OIDC_RP_CLIENT_ID`, and `OIDC_RP_CLIENT_SECRET`. Register `/oidc/callback/` at the provider. OIDC identities are linked by verified issuer and subject; a matching email does not link an existing local account. The actual provider callback still needs an integration test with your provider configuration.
|
||||
|
||||
Set `MCP_PUBLIC_URL` and `OAUTH_ISSUER_URL` to the public HTTPS MCP endpoint and Django origin. Route `/mcp` and `/.well-known/oauth-protected-resource/mcp` to port 8766, and OAuth routes to the Django process. Preserve the Authorization header. The MCP process and Django must use the same database and `DJANGO_SECRET_KEY`.
|
||||
|
||||
+17
-3
@@ -7,12 +7,16 @@ SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-local-developm
|
||||
DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1'
|
||||
if not DEBUG and (SECRET_KEY.startswith('django-insecure-') or len(SECRET_KEY) < 50):
|
||||
raise ImproperlyConfigured('Set a strong DJANGO_SECRET_KEY when DJANGO_DEBUG=0.')
|
||||
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
|
||||
ALLOWED_HOSTS = [host.strip() for host in os.environ.get(
|
||||
'DJANGO_ALLOWED_HOSTS',
|
||||
'localhost,127.0.0.1,100.91.62.59,projects.jorendegraaf.eu,project.jorendegraaf.eu',
|
||||
).split(',') if host.strip()]
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages',
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.staticfiles",
|
||||
"core",
|
||||
"dashboard",
|
||||
'projects',
|
||||
'oauth2_provider',
|
||||
]
|
||||
@@ -22,6 +26,7 @@ MIDDLEWARE = [
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'projects.middleware.ProfileTimezoneMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
@@ -40,6 +45,13 @@ USE_TZ = True
|
||||
STATICFILES_DIRS = [BASE_DIR / "dist"] if (BASE_DIR / "dist").exists() else []
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3'}}
|
||||
CACHES = {
|
||||
'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'},
|
||||
'weather': {
|
||||
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
|
||||
'LOCATION': os.environ.get('DASHBOARD_WEATHER_CACHE_DIR', '/tmp/django_dashboard_weather_cache'),
|
||||
},
|
||||
}
|
||||
LOGIN_URL = 'login'
|
||||
LOGIN_REDIRECT_URL = 'projects:list'
|
||||
LOGOUT_REDIRECT_URL = 'login'
|
||||
@@ -49,11 +61,12 @@ SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
||||
SECURE_SSL_REDIRECT = not DEBUG
|
||||
SECURE_HSTS_SECONDS = 31536000 if not DEBUG else 0
|
||||
CSRF_TRUSTED_ORIGINS = [item for item in os.environ.get('DJANGO_CSRF_TRUSTED_ORIGINS', '').split(',') if item]
|
||||
MCP_PUBLIC_URL = os.environ.get('MCP_PUBLIC_URL', 'http://127.0.0.1:8766/mcp')
|
||||
OAUTH_ISSUER_URL = os.environ.get('OAUTH_ISSUER_URL', 'http://127.0.0.1:8765/')
|
||||
MCP_PUBLIC_URL = os.environ.get('MCP_PUBLIC_URL', 'https://projects.jorendegraaf.eu/mcp').strip()
|
||||
OAUTH_ISSUER_URL = os.environ.get('OAUTH_ISSUER_URL', 'https://projects.jorendegraaf.eu').strip().rstrip('/')
|
||||
if not DEBUG and (not MCP_PUBLIC_URL.startswith('https://') or not OAUTH_ISSUER_URL.startswith('https://')):
|
||||
raise ImproperlyConfigured('MCP_PUBLIC_URL and OAUTH_ISSUER_URL must use HTTPS in production.')
|
||||
OAUTH2_PROVIDER = {
|
||||
'OIDC_ISS_ENDPOINT': f'{OAUTH_ISSUER_URL}/',
|
||||
'SCOPES': {'projects:read': 'Read projects and cards', 'projects:write': 'Create and edit projects and cards'},
|
||||
'DEFAULT_SCOPES': ['projects:read'],
|
||||
'ALLOWED_REDIRECT_URI_SCHEMES': ['http', 'https'] if DEBUG else ['https'],
|
||||
@@ -65,6 +78,7 @@ OAUTH2_PROVIDER = {
|
||||
'REFRESH_TOKEN_REUSE_PROTECTION': True,
|
||||
'DCR_ENABLED': True,
|
||||
'DCR_REGISTRATION_PERMISSION_CLASSES': ['oauth2_provider.dcr.IsAuthenticatedDCRPermission'],
|
||||
'OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED': ['none', 'client_secret_post', 'client_secret_basic'],
|
||||
'COMPLIANT_BCP_RFC9700_IMPLICIT_GRANT': True,
|
||||
'COMPLIANT_BCP_RFC9700_PASSWORD_GRANT': True,
|
||||
'COMPLIANT_BCP_RFC9700_AUTHZ_RESPONSE_ISS': True,
|
||||
|
||||
+2
-1
@@ -14,7 +14,8 @@ urlpatterns = [
|
||||
path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
|
||||
path('accounts/password/change/', auth_views.PasswordChangeView.as_view(template_name='projects/form.html', success_url='/projects/profile/'), name='password_change'),
|
||||
path('projects/', include('projects.urls')),
|
||||
path("", views.today, name="today"),
|
||||
path("", include('dashboard.urls')),
|
||||
path("examples/today/", views.today, name="today"),
|
||||
path("health/", views.health, name="health"),
|
||||
path("energy/", views.energy, name="energy"),
|
||||
path("home/", views.home, name="home"),
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/* Keep Bootstrap components in the same palette as the dashboard shell. */
|
||||
html[data-theme] {
|
||||
--bs-body-bg: var(--page-bg);
|
||||
--bs-body-color: var(--text);
|
||||
--bs-emphasis-color: var(--text);
|
||||
--bs-secondary-color: var(--text-secondary);
|
||||
--bs-secondary-bg: var(--surface-secondary);
|
||||
--bs-tertiary-bg: var(--surface);
|
||||
--bs-border-color: var(--border);
|
||||
--bs-border-color-translucent: var(--border);
|
||||
--bs-heading-color: var(--text);
|
||||
--bs-link-color: var(--accent);
|
||||
--bs-link-hover-color: var(--positive);
|
||||
--bs-code-color: var(--accent);
|
||||
--bs-form-valid-color: var(--positive);
|
||||
--bs-form-invalid-color: var(--negative);
|
||||
}
|
||||
|
||||
html[data-theme] .card,
|
||||
html[data-theme] .dropdown-menu,
|
||||
html[data-theme] .modal-content,
|
||||
html[data-theme] .list-group-item,
|
||||
html[data-theme] .accordion-item {
|
||||
--bs-card-bg: var(--surface);
|
||||
--bs-card-color: var(--text);
|
||||
background-color: var(--surface);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
html[data-theme] .card-header,
|
||||
html[data-theme] .card-footer,
|
||||
html[data-theme] .accordion-button {
|
||||
background-color: var(--surface-secondary);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
html[data-theme] .form-control,
|
||||
html[data-theme] .form-select,
|
||||
html[data-theme] select,
|
||||
html[data-theme] textarea,
|
||||
html[data-theme] input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]) {
|
||||
background-color: var(--surface);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
html[data-theme] main form p label {
|
||||
display: block;
|
||||
margin-bottom: .3rem;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
html[data-theme] main form p input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]):not([type="color"]),
|
||||
html[data-theme] main form p textarea,
|
||||
html[data-theme] main form p select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
padding: .5rem .75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: .5rem;
|
||||
}
|
||||
|
||||
html[data-theme] .form-control::placeholder,
|
||||
html[data-theme] textarea::placeholder,
|
||||
html[data-theme] input::placeholder {
|
||||
color: var(--text-muted);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
html[data-theme] .form-control:focus,
|
||||
html[data-theme] .form-select:focus,
|
||||
html[data-theme] select:focus,
|
||||
html[data-theme] textarea:focus,
|
||||
html[data-theme] input:focus:not([type="checkbox"]):not([type="radio"]) {
|
||||
background-color: var(--surface);
|
||||
color: var(--text);
|
||||
border-color: var(--focus);
|
||||
box-shadow: 0 0 0 .2rem color-mix(in srgb, var(--focus) 25%, transparent);
|
||||
}
|
||||
|
||||
html[data-theme] .form-control:disabled,
|
||||
html[data-theme] .form-select:disabled,
|
||||
html[data-theme] select:disabled,
|
||||
html[data-theme] input:disabled {
|
||||
background-color: var(--surface-secondary);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
html[data-theme] option {
|
||||
background-color: var(--surface);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
html[data-theme] .form-check-input {
|
||||
background-color: var(--surface);
|
||||
border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
html[data-theme] .form-check-input:checked {
|
||||
background-color: var(--positive);
|
||||
border-color: var(--positive);
|
||||
}
|
||||
|
||||
html[data-theme] .text-bg-light,
|
||||
html[data-theme] .bg-light {
|
||||
background-color: var(--surface-secondary) !important;
|
||||
color: var(--text) !important;
|
||||
}
|
||||
|
||||
html[data-theme] .text-muted,
|
||||
html[data-theme] .text-secondary {
|
||||
color: var(--text-secondary) !important;
|
||||
}
|
||||
|
||||
html[data-theme] .btn-outline-secondary {
|
||||
--bs-btn-color: var(--text-secondary);
|
||||
--bs-btn-border-color: var(--border);
|
||||
--bs-btn-hover-color: var(--text);
|
||||
--bs-btn-hover-bg: var(--surface-secondary);
|
||||
--bs-btn-hover-border-color: var(--text-muted);
|
||||
--bs-btn-active-color: var(--text);
|
||||
--bs-btn-active-bg: var(--surface-secondary);
|
||||
--bs-btn-active-border-color: var(--text-muted);
|
||||
}
|
||||
|
||||
html[data-theme] .btn-outline-danger {
|
||||
--bs-btn-color: var(--negative);
|
||||
--bs-btn-border-color: var(--negative);
|
||||
--bs-btn-hover-color: var(--page-bg);
|
||||
--bs-btn-hover-bg: var(--negative);
|
||||
--bs-btn-hover-border-color: var(--negative);
|
||||
}
|
||||
|
||||
html[data-theme] .btn-success {
|
||||
--bs-btn-bg: var(--positive);
|
||||
--bs-btn-border-color: var(--positive);
|
||||
--bs-btn-color: var(--page-bg);
|
||||
--bs-btn-hover-bg: var(--accent);
|
||||
--bs-btn-hover-border-color: var(--accent);
|
||||
--bs-btn-hover-color: var(--page-bg);
|
||||
}
|
||||
|
||||
html[data-theme] .table {
|
||||
--bs-table-bg: var(--surface);
|
||||
--bs-table-color: var(--text);
|
||||
--bs-table-border-color: var(--border);
|
||||
--bs-table-striped-bg: var(--surface-secondary);
|
||||
--bs-table-striped-color: var(--text);
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .form-select {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23b5c4b9' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e");
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html[data-theme="system"] .form-select {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23b5c4b9' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e");
|
||||
}
|
||||
}
|
||||
@@ -11,22 +11,19 @@
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
|
||||
{% vite_assets %}
|
||||
<link rel="stylesheet" href="{% static 'core/theme-bridge.css' %}">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to content</a>
|
||||
<div class="app-shell">
|
||||
<aside class="sidebar" aria-label="Main navigation">
|
||||
<a class="brand" href="{% url 'today' %}" aria-label="Common Ground home"><span class="brand-mark"><i class="bi bi-grid-1x2-fill"></i></span><span>common<span class="brand-light">ground</span><small>PERSONAL OVERVIEW</small></span></a>
|
||||
<a class="brand" href="{% url 'dashboard:index' %}" aria-label="Common Ground home"><span class="brand-mark"><i class="bi bi-grid-1x2-fill"></i></span><span>common<span class="brand-light">ground</span><small>PERSONAL OVERVIEW</small></span></a>
|
||||
<div class="nav-label">WORKSPACE</div>
|
||||
<nav class="side-nav">
|
||||
<a href="{% url 'today' %}" {% if section == 'today' %}aria-current="page"{% endif %}><i class="bi bi-layout-text-window-reverse"></i><span>Today</span></a>
|
||||
<a href="{% url 'health' %}" {% if section == 'health' %}aria-current="page"{% endif %}><i class="bi bi-heart"></i><span>Health</span></a>
|
||||
<a href="{% url 'energy' %}" {% if section == 'energy' %}aria-current="page"{% endif %}><i class="bi bi-lightning-charge"></i><span>Energy</span></a>
|
||||
<a href="{% url 'home' %}" {% if section == 'home' %}aria-current="page"{% endif %}><i class="bi bi-house"></i><span>Home</span></a>
|
||||
</nav>
|
||||
<nav class="side-nav"><a href="{% url 'dashboard:index' %}" {% if section == 'dashboard' %}aria-current="page"{% endif %}><i class="bi bi-grid-1x2"></i><span>Dashboard</span></a></nav>
|
||||
<details class="nav-submenu" {% if section == 'today' or section == 'health' or section == 'energy' or section == 'home' or section == 'showcase' %}open{% endif %}><summary><i class="bi bi-palette"></i> Design examples</summary><nav class="side-nav" aria-label="Design examples"><a href="{% url 'today' %}" {% if section == 'today' %}aria-current="page"{% endif %}>Today</a><a href="{% url 'health' %}" {% if section == 'health' %}aria-current="page"{% endif %}>Health</a><a href="{% url 'energy' %}" {% if section == 'energy' %}aria-current="page"{% endif %}>Energy</a><a href="{% url 'home' %}" {% if section == 'home' %}aria-current="page"{% endif %}>Home</a><a href="{% url 'showcase' %}" {% if section == 'showcase' %}aria-current="page"{% endif %}>Showcase</a></nav></details>
|
||||
{% if user.is_authenticated %}<div class="nav-label">PROJECTS</div><nav class="side-nav"><a href="{% url 'projects:list' %}" {% if section == 'projects' %}aria-current="page"{% endif %}><i class="bi bi-kanban"></i><span>All Projects</span></a>{% for nav_project in nav_projects %}<a href="{% url 'projects:board' nav_project.id %}"><i class="bi bi-folder"></i><span>{{ nav_project.name }}</span></a>{% endfor %}</nav><div class="nav-label">ACCOUNT</div><nav class="side-nav"><a href="{% url 'projects:profile' %}" {% if section == 'profile' %}aria-current="page"{% endif %}><i class="bi bi-person-circle"></i><span>Profile</span></a></nav>{% endif %}
|
||||
<div class="nav-label secondary-label">EXPLORE</div>
|
||||
<nav class="side-nav secondary-nav"><a href="{% url 'showcase' %}" {% if section == 'showcase' %}aria-current="page"{% endif %}><i class="bi bi-palette"></i><span>Showcase</span></a><span class="nav-disabled"><i class="bi bi-stars"></i>Insights <small>SOON</small></span><span class="nav-disabled"><i class="bi bi-gear"></i>Settings <small>SOON</small></span></nav>
|
||||
<nav class="side-nav secondary-nav"><span class="nav-disabled"><i class="bi bi-stars"></i>Insights <small>SOON</small></span><span class="nav-disabled"><i class="bi bi-gear"></i>Settings <small>SOON</small></span></nav>
|
||||
<div class="sidebar-bottom"><span class="demo-dot"></span><div><strong>{{ user.get_username }}</strong><small>Dashboard</small></div></div>
|
||||
</aside>
|
||||
<div class="main-column">
|
||||
@@ -34,5 +31,5 @@
|
||||
<main id="main" class="page-content">{% block content %}{% endblock %}</main>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="mobile-nav" aria-label="Mobile navigation"><a href="{% url 'today' %}" {% if section == 'today' %}aria-current="page"{% endif %}><i class="bi bi-layout-text-window-reverse"></i><span>Dashboard</span></a><a href="{% url 'projects:list' %}" {% if section == 'projects' %}aria-current="page"{% endif %}><i class="bi bi-kanban"></i><span>Projects</span></a><a href="{% url 'projects:profile' %}" {% if section == 'profile' %}aria-current="page"{% endif %}><i class="bi bi-person"></i><span>Profile</span></a><a href="{% url 'health' %}"><i class="bi bi-heart"></i><span>Health</span></a><a href="{% url 'home' %}"><i class="bi bi-house"></i><span>Home</span></a></nav>
|
||||
<nav class="mobile-nav" aria-label="Mobile navigation"><a href="{% url 'dashboard:index' %}" {% if section == 'dashboard' %}aria-current="page"{% endif %}><i class="bi bi-layout-text-window-reverse"></i><span>Dashboard</span></a><a href="{% url 'projects:list' %}" {% if section == 'projects' %}aria-current="page"{% endif %}><i class="bi bi-kanban"></i><span>Projects</span></a><a href="{% url 'projects:profile' %}" {% if section == 'profile' %}aria-current="page"{% endif %}><i class="bi bi-person"></i><span>Profile</span></a><a href="{% url 'today' %}"><i class="bi bi-palette"></i><span>Examples</span></a></nav>
|
||||
</body></html>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class DashboardConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "dashboard"
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Buienradar's documented coordinate-based two-hour rain forecast feed."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime, time as clock_time, timedelta, timezone
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from django.core.cache import caches
|
||||
|
||||
from .weather import coordinates
|
||||
|
||||
ENDPOINT = "https://gps.buienradar.nl/getrr.php"
|
||||
FRESH_SECONDS = 300
|
||||
STALE_SECONDS = 900
|
||||
AMSTERDAM = ZoneInfo("Europe/Amsterdam")
|
||||
LINE = re.compile(r"^(\d{3})\|([01]\d|2[0-3]):([0-5]\d)$")
|
||||
|
||||
|
||||
class RainUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def rain_label(intensity):
|
||||
# UI categories; Buienradar supplies the raw rain code, not these labels.
|
||||
if intensity < 0.1:
|
||||
return "None"
|
||||
if intensity < 2.5:
|
||||
return "Light"
|
||||
if intensity < 10:
|
||||
return "Moderate"
|
||||
return "Heavy"
|
||||
|
||||
|
||||
def parse_forecast(text, now=None):
|
||||
now = now or datetime.now(AMSTERDAM)
|
||||
if now.tzinfo is None:
|
||||
raise ValueError("Timezone-aware now required")
|
||||
rows = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if not 1 <= len(rows) <= 36:
|
||||
raise RainUnavailable("Rain forecast format is unavailable")
|
||||
points = []
|
||||
previous = None
|
||||
base_date = now.date()
|
||||
day_offset = 0
|
||||
for row in rows:
|
||||
match = LINE.fullmatch(row)
|
||||
if not match:
|
||||
raise RainUnavailable("Rain forecast format is unavailable")
|
||||
code, hour, minute = map(int, match.groups())
|
||||
if code > 255:
|
||||
raise RainUnavailable("Rain forecast format is unavailable")
|
||||
time = datetime.combine(base_date + timedelta(days=day_offset), clock_time(hour, minute), AMSTERDAM)
|
||||
if previous is None:
|
||||
if time - now > timedelta(hours=12):
|
||||
time -= timedelta(days=1)
|
||||
day_offset -= 1
|
||||
elif now - time > timedelta(hours=12):
|
||||
time += timedelta(days=1)
|
||||
day_offset += 1
|
||||
elif time <= previous:
|
||||
day_offset += 1
|
||||
time += timedelta(days=1)
|
||||
if previous is not None and not timedelta(minutes=0) < time - previous <= timedelta(minutes=10):
|
||||
raise RainUnavailable("Rain forecast timing is unavailable")
|
||||
previous = time
|
||||
intensity = 0 if code == 0 else 10 ** ((code - 109) / 32)
|
||||
# The upper end of the 0-255 scale is saturated; an exact rate would imply false precision.
|
||||
points.append({"time": time.isoformat(), "mm_per_hour": round(intensity, 2) if intensity < 100 else None, "label": rain_label(intensity)})
|
||||
return points
|
||||
|
||||
|
||||
def request_rain(lat, lon):
|
||||
url = f"{ENDPOINT}?{urlencode({'lat': lat, 'lon': lon})}"
|
||||
request = Request(url, headers={"User-Agent": "CommonGroundDashboard/1.0"})
|
||||
with urlopen(request, timeout=8) as response:
|
||||
if response.status != 200:
|
||||
raise RainUnavailable("Rain service is temporarily unavailable")
|
||||
body = response.read(10000)
|
||||
try:
|
||||
points = parse_forecast(body.decode("ascii"))
|
||||
except UnicodeDecodeError as exc:
|
||||
raise RainUnavailable("Rain forecast format is unavailable") from exc
|
||||
return {"points": points, "fetched_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
def get_rain(latitude, longitude):
|
||||
lat, lon = coordinates(latitude, longitude)
|
||||
# The documented feed covers the Netherlands; avoid meaningless global requests.
|
||||
if not (50.5 <= lat <= 53.7 and 3.0 <= lon <= 7.3):
|
||||
raise ValueError("Buienradar's local rain forecast is available for locations in the Netherlands")
|
||||
key = hashlib.sha256(f"buienradar:v1:{lat:.2f}:{lon:.2f}".encode()).hexdigest()
|
||||
cache = caches["weather"]
|
||||
fresh = cache.get(f"fresh:{key}")
|
||||
if fresh is not None:
|
||||
return {**fresh, "stale": False}
|
||||
stale = cache.get(f"stale:{key}")
|
||||
lock = f"lock:{key}"
|
||||
if not cache.add(lock, True, timeout=20):
|
||||
if stale is not None:
|
||||
return {**stale, "stale": True}
|
||||
raise RainUnavailable("Rain forecast is being refreshed. Try again shortly")
|
||||
try:
|
||||
payload = request_rain(lat, lon)
|
||||
cache.set(f"fresh:{key}", payload, timeout=FRESH_SECONDS)
|
||||
cache.set(f"stale:{key}", payload, timeout=STALE_SECONDS)
|
||||
return {**payload, "stale": False}
|
||||
except (OSError, RainUnavailable) as exc:
|
||||
if stale is not None:
|
||||
return {**stale, "stale": True}
|
||||
raise RainUnavailable("Rain service is temporarily unavailable") from exc
|
||||
finally:
|
||||
cache.delete(lock)
|
||||
@@ -0,0 +1,19 @@
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
initial = True
|
||||
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
|
||||
operations = [
|
||||
migrations.CreateModel(name="DashboardLayout", fields=[
|
||||
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||
("page", models.SlugField(max_length=80)),
|
||||
("revision", models.PositiveIntegerField(default=0)),
|
||||
("widgets", models.JSONField(default=list)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
("user", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
]),
|
||||
migrations.AddConstraint(model_name="dashboardlayout", constraint=models.UniqueConstraint(fields=("user", "page"), name="unique_dashboard_user_page")),
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class DashboardLayout(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
page = models.SlugField(max_length=80)
|
||||
revision = models.PositiveIntegerField(default=0)
|
||||
widgets = models.JSONField(default=list)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=["user", "page"], name="unique_dashboard_user_page")]
|
||||
@@ -0,0 +1,24 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WidgetType:
|
||||
id: str
|
||||
title: str
|
||||
description: str
|
||||
icon: str
|
||||
template: str
|
||||
default_span: int = 1
|
||||
multiple: bool = False
|
||||
settings_keys: tuple = ()
|
||||
|
||||
|
||||
WIDGETS = {
|
||||
widget.id: widget for widget in (
|
||||
WidgetType("welcome", "Welcome", "A starting point for your space", "bi-sun", "dashboard/widgets/welcome.html", 2),
|
||||
WidgetType("notes", "Quick notes", "A short personal note", "bi-sticky", "dashboard/widgets/notes.html", 1, True, ("text",)),
|
||||
WidgetType("shortcuts", "Shortcuts", "Links to useful pages", "bi-grid", "dashboard/widgets/shortcuts.html"),
|
||||
WidgetType("open_meteo", "Weather forecast", "Current weather and hourly outlook from Open-Meteo", "bi-cloud-sun", "dashboard/widgets/open_meteo.html", 2),
|
||||
WidgetType("buienradar", "Rain radar", "Netherlands radar and local rain forecast from Buienradar", "bi-cloud-rain", "dashboard/widgets/buienradar.html", 2),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.rain-widget{color:var(--text)}.rain-location{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.rain-location strong,.rain-location small{display:block}.rain-location small{font-size:11px;color:var(--text-muted)}.rain-location>div:last-child{display:flex;gap:6px;flex-wrap:wrap}.rain-manual{margin:12px 0;color:var(--text-secondary)}.rain-manual summary{cursor:pointer;font-size:11px;font-weight:700}.rain-manual form{display:flex;gap:8px;align-items:end;flex-wrap:wrap;padding:12px 0}.rain-manual label{display:grid;gap:4px;font-size:11px;font-weight:700}.rain-manual input{max-width:130px;padding:8px;border:1px solid var(--border);border-radius:7px;background:var(--surface);color:var(--text)}.rain-manual p{font-size:11px}.rain-layout{display:grid;grid-template-columns:minmax(240px,320px) minmax(0,1fr);gap:22px;margin-top:15px;border-top:1px solid var(--border);padding-top:18px}.rain-radar-heading,.rain-forecast-heading{display:flex;align-items:baseline;justify-content:space-between;gap:8px}.rain-radar-heading h3,.rain-forecast-heading h3{font-size:13px;margin:0 0 9px}.rain-radar-heading span,.rain-forecast-heading span{font-size:10px;color:var(--text-muted)}.rain-radar-frame{min-height:230px;border:1px solid var(--border);border-radius:var(--radius-sm);overflow:hidden;background:var(--surface-secondary);display:grid;place-items:center}.rain-radar-frame img{display:block;width:100%;height:auto}.rain-radar-frame iframe{display:block;max-width:100%;border:0}.rain-radar-frame [hidden],.rain-dialog [hidden],.rain-widget [hidden]{display:none}.rain-radar-actions,.rain-step-actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:9px}.rain-caveat{font-size:10px;color:var(--text-muted);margin:9px 0 0!important}.rain-status{font-size:11px;color:var(--text-secondary);margin:4px 0 12px!important}.rain-status.stale{color:var(--warning)}.rain-reading{display:grid;gap:3px;padding:12px;background:var(--surface-secondary);border-radius:var(--radius-sm)}.rain-reading strong{font-size:16px}.rain-reading span{font:800 25px Manrope,sans-serif}.rain-reading small{color:var(--text-muted)}.rain-bars{display:flex;align-items:end;gap:3px;height:85px;margin:18px 0 9px;border-bottom:1px solid var(--border)}.rain-bar{flex:1;min-width:3px;background:var(--accent);border-radius:3px 3px 0 0;opacity:.55}.rain-bar.selected{opacity:1;background:var(--positive);outline:2px solid var(--focus);outline-offset:1px}.rain-scrubber-label{display:block;font-size:11px;font-weight:700;margin-bottom:4px}.rain-widget input[type=range]{display:block;width:100%;accent-color:var(--accent);min-height:32px}.rain-step-actions .button{font-size:10px}.rain-credit{margin-top:17px;padding-top:9px;border-top:1px solid var(--border);font-size:10px;color:var(--text-muted)}.rain-credit a{text-decoration:underline;text-underline-offset:2px}.rain-dialog{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface);color:var(--text);padding:15px;max-width:min(96vw,600px);max-height:96vh;overflow:auto}.rain-dialog::backdrop{background:rgba(0,0,0,.72)}.rain-dialog-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:10px}.rain-dialog img{display:block;width:min(100%,500px);height:auto}.rain-dialog iframe{display:block;max-width:100%;border:0;margin:auto}@media(max-width:900px){.rain-layout{grid-template-columns:1fr}.rain-radar-frame{max-width:360px}.rain-radar-frame img{max-width:360px}.rain-radar-frame iframe{max-width:256px}}@media(max-width:760px){.rain-widget .button{min-height:44px}.rain-dialog{width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;border-radius:0;margin:0}.rain-radar-frame{max-width:100%}}
|
||||
@@ -0,0 +1,124 @@
|
||||
(() => {
|
||||
const gadget = 'https://gadgets.buienradar.nl/gadget/radarfivedays';
|
||||
const csrf = () => decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '');
|
||||
const time = iso => new Intl.DateTimeFormat(undefined, { timeZone: 'Europe/Amsterdam', weekday: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(iso));
|
||||
function mount(card) {
|
||||
const root = card.querySelector('.rain-widget');
|
||||
if (!root) return () => {};
|
||||
const controller = new AbortController();
|
||||
const status = root.querySelector('[data-rain-status]');
|
||||
const content = root.querySelector('[data-rain-content]');
|
||||
const slider = root.querySelector('[data-rain-slider]');
|
||||
const bars = root.querySelector('[data-rain-bars]');
|
||||
const play = root.querySelector('[data-rain-play]');
|
||||
const image = root.querySelector('[data-rain-image]');
|
||||
const animation = root.querySelector('[data-rain-animation]');
|
||||
const dialog = root.querySelector('[data-rain-dialog]');
|
||||
const dialogImage = root.querySelector('[data-rain-dialog-image]');
|
||||
const dialogAnimation = root.querySelector('[data-rain-dialog-animation]');
|
||||
let request = null;
|
||||
let latest = null;
|
||||
let playing = false;
|
||||
let lastFocus = null;
|
||||
function setPlaying(next) {
|
||||
playing = next;
|
||||
play.textContent = next ? 'Pause animation' : 'Play animation';
|
||||
play.setAttribute('aria-pressed', String(next));
|
||||
image.hidden = next; animation.hidden = !next;
|
||||
dialogImage.hidden = next; dialogAnimation.hidden = !next;
|
||||
if (next) {
|
||||
animation.src = gadget;
|
||||
if (dialog.open) dialogAnimation.src = gadget;
|
||||
} else {
|
||||
animation.removeAttribute('src');
|
||||
dialogAnimation.removeAttribute('src');
|
||||
}
|
||||
}
|
||||
function select(index) {
|
||||
if (!latest?.points?.length) return;
|
||||
index = Math.max(0, Math.min(latest.points.length - 1, Number(index)));
|
||||
slider.value = String(index);
|
||||
const point = latest.points[index];
|
||||
const at = time(point.time);
|
||||
const description = point.label === 'None' ? 'No rain' : `${point.label} rain`;
|
||||
root.querySelector('[data-rain-class]').textContent = description;
|
||||
const amount = point.mm_per_hour == null ? 'Very heavy · rate above chart scale' : `${Number(point.mm_per_hour).toFixed(2)} mm/h`;
|
||||
root.querySelector('[data-rain-amount]').textContent = amount;
|
||||
root.querySelector('[data-rain-time]').textContent = `${at} · forecast`;
|
||||
slider.setAttribute('aria-valuetext', `${at}, ${description.toLowerCase()}, ${point.mm_per_hour == null ? 'rate above chart scale' : `${Number(point.mm_per_hour).toFixed(2)} millimetres per hour`}, forecast`);
|
||||
bars.querySelectorAll('.rain-bar').forEach((bar, position) => bar.classList.toggle('selected', position === index));
|
||||
root.querySelector('[data-rain-prev]').disabled = index === 0;
|
||||
root.querySelector('[data-rain-next]').disabled = index === latest.points.length - 1;
|
||||
}
|
||||
function render(data) {
|
||||
latest = data;
|
||||
bars.replaceChildren();
|
||||
const points = data.points || [];
|
||||
if (!points.length) throw new Error('Rain forecast has no time points');
|
||||
const peak = Math.max(2.5, ...points.map(point => point.mm_per_hour == null ? 100 : Number(point.mm_per_hour) || 0));
|
||||
points.forEach(point => {
|
||||
const bar = document.createElement('span');
|
||||
bar.className = 'rain-bar';
|
||||
bar.style.height = `${Math.max(3, Math.min(100, (point.mm_per_hour == null ? 100 : Number(point.mm_per_hour)) / peak * 100))}%`;
|
||||
bars.append(bar);
|
||||
});
|
||||
slider.max = String(points.length - 1);
|
||||
content.hidden = false;
|
||||
select(Math.min(Number(slider.value), points.length - 1));
|
||||
root.querySelector('[data-rain-updated]').textContent = `Forecast fetched ${new Date(data.fetched_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
|
||||
status.textContent = data.stale ? 'Showing an older rain forecast. Live refresh is unavailable.' : 'Rain forecast ready';
|
||||
status.classList.toggle('stale', data.stale);
|
||||
}
|
||||
async function load() {
|
||||
request?.abort();
|
||||
request = new AbortController();
|
||||
const location = window.DashboardLocation.get();
|
||||
root.querySelector('[data-rain-location]').textContent = location.name;
|
||||
status.textContent = latest ? 'Refreshing rain forecast…' : 'Loading rain forecast…';
|
||||
try {
|
||||
const response = await fetch(root.dataset.rainUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf() }, body: JSON.stringify(location), signal: request.signal });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Rain forecast unavailable');
|
||||
render(data);
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
status.textContent = `${error.message}. ${latest ? 'Showing the last loaded forecast.' : 'Try again later.'}`;
|
||||
status.classList.add('stale');
|
||||
content.hidden = !latest;
|
||||
}
|
||||
}
|
||||
play.addEventListener('click', () => setPlaying(!playing), { signal: controller.signal });
|
||||
root.querySelector('[data-rain-fullscreen]').addEventListener('click', () => {
|
||||
lastFocus = document.activeElement;
|
||||
if (typeof dialog.showModal === 'function') {
|
||||
dialog.showModal();
|
||||
if (playing) dialogAnimation.src = gadget;
|
||||
root.querySelector('[data-rain-close]').focus();
|
||||
} else {
|
||||
window.open('https://www.buienradar.nl/', '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
}, { signal: controller.signal });
|
||||
function closeDialog() { dialog.close(); dialogAnimation.removeAttribute('src'); lastFocus?.focus(); }
|
||||
root.querySelector('[data-rain-close]').addEventListener('click', closeDialog, { signal: controller.signal });
|
||||
dialog.addEventListener('close', () => { dialogAnimation.removeAttribute('src'); lastFocus?.focus(); }, { signal: controller.signal });
|
||||
dialog.addEventListener('click', event => { if (event.target === dialog) closeDialog(); }, { signal: controller.signal });
|
||||
slider.addEventListener('input', () => select(slider.value), { signal: controller.signal });
|
||||
root.querySelector('[data-rain-prev]').addEventListener('click', () => select(Number(slider.value) - 1), { signal: controller.signal });
|
||||
root.querySelector('[data-rain-next]').addEventListener('click', () => select(Number(slider.value) + 1), { signal: controller.signal });
|
||||
root.querySelector('[data-rain-geolocate]').addEventListener('click', async () => {
|
||||
status.textContent = 'Requesting browser location…';
|
||||
try { await window.DashboardLocation.locate(); } catch (error) { status.textContent = error.message; }
|
||||
}, { signal: controller.signal });
|
||||
root.querySelector('[data-rain-manual]').addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
try { window.DashboardLocation.set(Object.fromEntries(new FormData(event.target))); } catch (error) { status.textContent = error.message; }
|
||||
}, { signal: controller.signal });
|
||||
root.querySelector('[data-rain-refresh]').addEventListener('click', load, { signal: controller.signal });
|
||||
image.addEventListener('error', () => { image.alt = 'Radar image unavailable. Use the Buienradar link below.'; }, { signal: controller.signal });
|
||||
const unsubscribe = window.DashboardLocation.subscribe(load);
|
||||
const timer = setInterval(load, 300000);
|
||||
load();
|
||||
return () => { controller.abort(); request?.abort(); clearInterval(timer); unsubscribe(); setPlaying(false); if (dialog.open) dialog.close(); };
|
||||
}
|
||||
window.DashboardBuienradar = { mount };
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,219 @@
|
||||
(() => {
|
||||
const grid = document.querySelector('#widget-grid');
|
||||
if (!grid) return;
|
||||
const editButton = document.querySelector('#edit-layout');
|
||||
const resetButton = document.querySelector('#reset-layout');
|
||||
const status = document.querySelector('#layout-status');
|
||||
const catalogue = document.querySelector('#widget-catalogue');
|
||||
const backdrop = document.querySelector('#catalogue-backdrop');
|
||||
const search = document.querySelector('#widget-search');
|
||||
let editing = false;
|
||||
let dirty = false;
|
||||
let dragged = null;
|
||||
let catalogueDraggedType = null;
|
||||
let dropBefore = null;
|
||||
let dropAfter = null;
|
||||
let saving = false;
|
||||
let previousFocus = null;
|
||||
const lifecycle = new WeakMap();
|
||||
const indicator = document.createElement('div');
|
||||
indicator.className = 'widget-drop-indicator';
|
||||
indicator.setAttribute('aria-hidden', 'true');
|
||||
grid.append(indicator);
|
||||
const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain' };
|
||||
const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar' };
|
||||
const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2 };
|
||||
const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false };
|
||||
|
||||
function setStatus(message, error = false) {
|
||||
status.textContent = message;
|
||||
status.classList.toggle('error', error);
|
||||
}
|
||||
function cards() { return [...grid.querySelectorAll(':scope > .widget-card')]; }
|
||||
function updateEmpty() { document.querySelector('#empty-layout').hidden = cards().length > 0; }
|
||||
function markDirty() { dirty = true; setStatus('Unsaved layout changes'); updateEmpty(); }
|
||||
function mount(root) {
|
||||
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
|
||||
targets.forEach(card => {
|
||||
if (lifecycle.has(card)) return;
|
||||
const controller = new AbortController();
|
||||
if (card.dataset.widgetType === 'notes') {
|
||||
card.querySelector('[data-setting="text"]')?.addEventListener('input', event => {
|
||||
card.querySelector('.note-preview').textContent = event.target.value || 'Add a note in widget settings.';
|
||||
markDirty();
|
||||
}, { signal: controller.signal });
|
||||
}
|
||||
const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : null;
|
||||
lifecycle.set(card, () => { controller.abort(); widgetCleanup?.(); });
|
||||
card.dispatchEvent(new CustomEvent('dashboard:widget-mounted', { bubbles: true }));
|
||||
});
|
||||
}
|
||||
function unmount(root) {
|
||||
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
|
||||
targets.forEach(card => { lifecycle.get(card)?.(); lifecycle.delete(card); card.dispatchEvent(new CustomEvent('dashboard:widget-unmounted', { bubbles: true })); });
|
||||
}
|
||||
document.addEventListener('htmx:beforeCleanupElement', event => unmount(event.detail.elt));
|
||||
document.addEventListener('htmx:afterSwap', event => mount(event.detail.elt));
|
||||
document.addEventListener('dashboard:mount', event => mount(event.target));
|
||||
document.addEventListener('dashboard:unmount', event => unmount(event.target));
|
||||
function clearDrop() {
|
||||
dropBefore = dropAfter = null;
|
||||
indicator.classList.remove('visible', 'invalid');
|
||||
cards().forEach(card => card.classList.remove('drop-target'));
|
||||
}
|
||||
function showDrop(target, before, type) {
|
||||
const valid = !type || multiple[type] || !cards().some(card => card.dataset.widgetType === type);
|
||||
const rect = target?.getBoundingClientRect() || grid.getBoundingClientRect();
|
||||
const parent = grid.getBoundingClientRect();
|
||||
const top = target ? rect.top - parent.top + (before ? 0 : rect.height) : grid.scrollHeight;
|
||||
indicator.style.top = `${top}px`;
|
||||
indicator.style.left = `${target ? rect.left - parent.left : 0}px`;
|
||||
indicator.style.width = `${target ? rect.width : grid.clientWidth}px`;
|
||||
indicator.textContent = valid ? (target ? `Insert ${before ? 'before' : 'after'} ${target.querySelector('h2')?.textContent}` : 'Add at end') : 'Already on this page';
|
||||
indicator.classList.add('visible');
|
||||
indicator.classList.toggle('invalid', !valid);
|
||||
cards().forEach(card => card.classList.toggle('drop-target', card === target && valid));
|
||||
dropBefore = valid && before ? target : null;
|
||||
dropAfter = valid && !before ? target : null;
|
||||
if (!valid) { dropBefore = dropAfter = null; }
|
||||
return valid;
|
||||
}
|
||||
function insertAtDrop(card) {
|
||||
if (dropBefore) grid.insertBefore(card, dropBefore);
|
||||
else if (dropAfter) grid.insertBefore(card, dropAfter.nextElementSibling);
|
||||
else grid.insertBefore(card, indicator);
|
||||
clearDrop();
|
||||
}
|
||||
function openCatalogue() {
|
||||
previousFocus = document.activeElement;
|
||||
catalogue.removeAttribute('inert');
|
||||
catalogue.setAttribute('aria-hidden', 'false');
|
||||
catalogue.classList.add('open');
|
||||
backdrop.hidden = false;
|
||||
document.querySelector('#catalogue-toggle').setAttribute('aria-expanded', 'true');
|
||||
search.focus();
|
||||
}
|
||||
function closeCatalogue() {
|
||||
catalogue.classList.remove('open');
|
||||
catalogue.setAttribute('aria-hidden', 'true');
|
||||
catalogue.setAttribute('inert', '');
|
||||
backdrop.hidden = true;
|
||||
document.querySelector('#catalogue-toggle').setAttribute('aria-expanded', 'false');
|
||||
previousFocus?.focus();
|
||||
}
|
||||
function widgetMarkup(type) {
|
||||
const icon = icons[type], title = titles[type];
|
||||
const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'notes' ? '<p class="note-preview">Add a note in widget settings.</p>' : type === 'welcome' ? '<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>' : '<nav class="widget-shortcuts" aria-label="Quick links"><a href="/projects/">Projects ↗</a><a href="/examples/today/">Design examples ↗</a></nav>';
|
||||
return `<header class="widget-card-head"><div><i class="bi ${icon}" aria-hidden="true"></i><h2>${title}</h2></div><div class="widget-controls"><button type="button" data-move="left" aria-label="Move ${title} earlier" title="Move earlier">←</button><button type="button" data-move="right" aria-label="Move ${title} later" title="Move later">→</button><button type="button" data-span-toggle aria-label="Resize ${title}" title="Resize">↔</button><button type="button" data-settings-toggle aria-label="Settings for ${title}" title="Settings"><i class="bi bi-sliders"></i></button><button type="button" data-remove aria-label="Remove ${title}" title="Remove"><i class="bi bi-x-lg"></i></button><span class="drag-handle" draggable="true" aria-hidden="true"><i class="bi bi-grip-vertical"></i></span></div></header><div class="widget-body">${body}</div><div class="widget-settings" hidden>${type === 'notes' ? '<label>Note text <textarea data-setting="text" maxlength="1000"></textarea></label>' : '<p>No settings for this widget.</p>'}</div>`;
|
||||
}
|
||||
function add(type, before = null) {
|
||||
if (!editing || !titles[type]) return;
|
||||
if (!multiple[type] && cards().some(card => card.dataset.widgetType === type)) {
|
||||
setStatus(`${titles[type]} is already on this page.`, true); return;
|
||||
}
|
||||
const card = document.createElement('article');
|
||||
card.className = 'widget-card content-card';
|
||||
card.dataset.widgetPlatform = 'bottom';
|
||||
card.dataset.instanceId = crypto.randomUUID();
|
||||
card.dataset.widgetType = type;
|
||||
card.dataset.span = String(spans[type]);
|
||||
card.innerHTML = widgetMarkup(type);
|
||||
grid.insertBefore(card, before || indicator);
|
||||
mount(card);
|
||||
markDirty();
|
||||
card.querySelector('[data-move]').focus();
|
||||
}
|
||||
function enterEdit() {
|
||||
editing = true; grid.classList.add('editing');
|
||||
resetButton.hidden = false;
|
||||
editButton.textContent = 'Done';
|
||||
setStatus('Editing layout. Drag cards or use their move controls.');
|
||||
}
|
||||
async function finishEdit() {
|
||||
if (saving) return;
|
||||
if (dirty) {
|
||||
saving = true;
|
||||
editButton.disabled = true;
|
||||
setStatus('Saving layout…');
|
||||
const widgets = cards().map((card, order) => ({
|
||||
id: card.dataset.instanceId, type: card.dataset.widgetType, order,
|
||||
span: Number(card.dataset.span), visible: true,
|
||||
settings: card.dataset.widgetType === 'notes' ? { text: card.querySelector('textarea')?.value || '' } : {},
|
||||
}));
|
||||
try {
|
||||
const response = await fetch(grid.dataset.saveUrl, { method: 'PUT', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '') }, body: JSON.stringify({ revision: Number(grid.dataset.revision), widgets }) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || 'Could not save layout');
|
||||
grid.dataset.revision = result.revision;
|
||||
dirty = false;
|
||||
} catch (error) { setStatus(`${error.message} Your edits are still here. Try Done again.`, true); return; }
|
||||
finally { saving = false; editButton.disabled = false; }
|
||||
}
|
||||
editing = false; grid.classList.remove('editing', 'dragging');
|
||||
resetButton.hidden = true;
|
||||
clearDrop();
|
||||
cards().forEach(card => { card.querySelector('.widget-settings').hidden = true; });
|
||||
editButton.textContent = 'Edit layout';
|
||||
setStatus('Layout saved');
|
||||
closeCatalogueIfOpen();
|
||||
}
|
||||
function closeCatalogueIfOpen() { if (catalogue.classList.contains('open')) closeCatalogue(); }
|
||||
editButton.addEventListener('click', () => editing ? finishEdit() : enterEdit());
|
||||
resetButton.addEventListener('click', () => {
|
||||
if (!confirm('Reset this page to its default widgets? This replaces your layout.')) return;
|
||||
unmount(grid);
|
||||
cards().forEach(card => card.remove());
|
||||
add('welcome'); add('shortcuts');
|
||||
setStatus('Default layout ready. Select Done to save.');
|
||||
});
|
||||
document.querySelector('#catalogue-toggle').addEventListener('click', openCatalogue);
|
||||
document.querySelector('#catalogue-close').addEventListener('click', closeCatalogue);
|
||||
backdrop.addEventListener('click', closeCatalogue);
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape' && catalogue.classList.contains('open')) closeCatalogue();
|
||||
if (event.key === 'Tab' && catalogue.classList.contains('open')) {
|
||||
const focusable = [...catalogue.querySelectorAll('button:not([disabled]), input')].filter(el => !el.closest('[hidden]'));
|
||||
const first = focusable[0], last = focusable.at(-1);
|
||||
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
|
||||
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
|
||||
}
|
||||
});
|
||||
search.addEventListener('input', () => {
|
||||
const query = search.value.trim().toLowerCase();
|
||||
catalogue.querySelectorAll('.catalogue-entry').forEach(entry => { entry.hidden = !(entry.dataset.title.includes(query) || entry.dataset.description.includes(query)); });
|
||||
});
|
||||
catalogue.addEventListener('click', event => { const button = event.target.closest('[data-add]'); if (button) { if (!editing) enterEdit(); add(button.dataset.add); closeCatalogue(); } });
|
||||
grid.addEventListener('click', event => {
|
||||
const button = event.target.closest('button');
|
||||
const card = button?.closest('.widget-card');
|
||||
if (!editing || !card) return;
|
||||
if (button.hasAttribute('data-remove')) { unmount(card); card.remove(); markDirty(); setStatus(`${card.querySelector('h2').textContent} removed. Unsaved layout changes.`); editButton.focus(); }
|
||||
else if (button.hasAttribute('data-span-toggle')) { card.dataset.span = card.dataset.span === '2' ? '1' : '2'; markDirty(); setStatus(`${card.querySelector('h2').textContent} now spans ${card.dataset.span} ${card.dataset.span === '1' ? 'column' : 'columns'}. Unsaved layout changes.`); }
|
||||
else if (button.hasAttribute('data-settings-toggle')) { const panel = card.querySelector('.widget-settings'); panel.hidden = !panel.hidden; if (!panel.hidden) panel.querySelector('textarea')?.focus(); }
|
||||
else if (button.hasAttribute('data-move')) { const list = cards(); const index = list.indexOf(card); const next = index + (button.dataset.move === 'left' ? -1 : 1); if (next >= 0 && next < list.length) { grid.insertBefore(card, button.dataset.move === 'left' ? list[next] : list[next].nextSibling); markDirty(); setStatus(`${card.querySelector('h2').textContent} moved to position ${next + 1} of ${list.length}. Unsaved layout changes.`); button.focus(); } }
|
||||
});
|
||||
grid.addEventListener('dragstart', event => { if (!editing || !event.target.closest('.drag-handle')) { event.preventDefault(); return; } dragged = event.target.closest('.widget-card'); grid.classList.add('dragging'); event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', dragged.dataset.instanceId); });
|
||||
grid.addEventListener('dragover', event => {
|
||||
if (!editing || (!dragged && !event.dataTransfer.types.includes('application/widget-type'))) return;
|
||||
event.preventDefault();
|
||||
const target = event.target.closest('.widget-card');
|
||||
const type = catalogueDraggedType;
|
||||
const before = target ? event.clientY < target.getBoundingClientRect().top + target.getBoundingClientRect().height / 2 : false;
|
||||
showDrop(target, before, type);
|
||||
});
|
||||
grid.addEventListener('drop', event => {
|
||||
if (!editing) return;
|
||||
const type = catalogueDraggedType || event.dataTransfer.getData('application/widget-type');
|
||||
if (!dragged && !type) return;
|
||||
event.preventDefault();
|
||||
if (type) { if (!indicator.classList.contains('invalid')) { const before = dropBefore; const after = dropAfter; clearDrop(); add(type, before || after?.nextElementSibling || null); } }
|
||||
else if (dragged) { insertAtDrop(dragged); markDirty(); setStatus(`${dragged.querySelector('h2').textContent} moved to position ${cards().indexOf(dragged) + 1}. Unsaved layout changes.`); }
|
||||
dragged = null; catalogueDraggedType = null; grid.classList.remove('dragging'); closeCatalogueIfOpen();
|
||||
});
|
||||
grid.addEventListener('dragleave', event => { if (!grid.contains(event.relatedTarget)) clearDrop(); });
|
||||
grid.addEventListener('dragend', () => { dragged = null; grid.classList.remove('dragging'); clearDrop(); });
|
||||
catalogue.addEventListener('dragstart', event => { const entry = event.target.closest('.catalogue-entry'); if (entry) { if (!editing) enterEdit(); catalogueDraggedType = entry.dataset.widgetType; event.dataTransfer.setData('application/widget-type', catalogueDraggedType); backdrop.hidden = true; } });
|
||||
catalogue.addEventListener('dragend', () => { catalogueDraggedType = null; clearDrop(); if (catalogue.classList.contains('open')) backdrop.hidden = false; });
|
||||
mount(grid);
|
||||
updateEmpty();
|
||||
})();
|
||||
@@ -0,0 +1,26 @@
|
||||
(() => {
|
||||
let location = { latitude: 52.96, longitude: 5.92, name: 'Heerenveen' };
|
||||
let permissionDenied = false;
|
||||
const listeners = new Set();
|
||||
function set(next) {
|
||||
const latitude = Number(next.latitude), longitude = Number(next.longitude);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude) || Math.abs(latitude) > 90 || Math.abs(longitude) > 180) throw new Error('Choose valid coordinates.');
|
||||
location = { latitude: Math.round(latitude * 100) / 100, longitude: Math.round(longitude * 100) / 100, name: next.name || 'Chosen location' };
|
||||
listeners.forEach(listener => listener({ ...location }));
|
||||
}
|
||||
function locate() {
|
||||
if (permissionDenied) return Promise.reject(new Error('Location permission was denied. Enter coordinates manually or change browser permissions.'));
|
||||
if (!navigator.geolocation) return Promise.reject(new Error('Browser location is unavailable. Enter coordinates manually.'));
|
||||
return new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(position => {
|
||||
set({ latitude: position.coords.latitude, longitude: position.coords.longitude, name: 'Your approximate location' });
|
||||
resolve({ ...location });
|
||||
}, error => {
|
||||
if (error.code === 1) permissionDenied = true;
|
||||
reject(new Error(error.code === 1 ? 'Location permission was denied. Enter coordinates manually or change browser permissions.' : 'Could not determine your location. Enter coordinates manually.'));
|
||||
}, { enableHighAccuracy: false, timeout: 10000, maximumAge: 900000 }));
|
||||
}
|
||||
window.DashboardLocation = {
|
||||
get: () => ({ ...location }), set, locate,
|
||||
subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
.weather-widget{color:var(--text)}.weather-location{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}.weather-location>div:last-child{display:flex;gap:6px;flex-wrap:wrap}.weather-location strong,.weather-location small{display:block}.weather-location small{color:var(--text-muted);font-size:11px}.weather-manual{margin:12px 0;color:var(--text-secondary)}.weather-manual summary{cursor:pointer;font-weight:700;font-size:11px}.weather-manual form{display:flex;gap:8px;align-items:end;flex-wrap:wrap;padding:12px 0}.weather-manual label{display:grid;gap:4px;font-size:11px;font-weight:700}.weather-manual input{max-width:130px;padding:8px;border:1px solid var(--border);border-radius:7px;background:var(--surface);color:var(--text)}.weather-manual p{font-size:11px}.weather-status{margin:12px 0!important;font-size:11px;color:var(--text-secondary)}.weather-status.stale{color:var(--warning)}.weather-current{display:flex;justify-content:space-between;gap:20px;flex-wrap:wrap;border-top:1px solid var(--border);padding:20px 0}.weather-current>div:first-child{display:grid;gap:1px}.weather-temperature{font:800 clamp(35px,5vw,56px)/1.1 Manrope,sans-serif;color:var(--text)}.weather-current strong{font-size:14px}.weather-current small{color:var(--text-muted)}.weather-current dl,.weather-summary dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px;margin:0}.weather-current dl{min-width:min(100%,290px)}.weather-current dt,.weather-summary dt{font-size:10px;color:var(--text-muted);font-weight:700}.weather-current dd,.weather-summary dd{margin:0;font-size:12px;font-weight:700}.weather-summary{background:var(--surface-secondary);border-radius:var(--radius-sm);padding:15px}.weather-summary h3,.weather-hours-heading h3{font-size:13px;margin:0 0 10px}.weather-hours-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:18px 0 8px}.weather-hours-heading h3{margin:0}.weather-hours{display:flex;gap:7px;overflow-x:auto;scroll-snap-type:x proximity;padding:5px 3px 12px}.weather-hour{flex:0 0 84px;display:grid;justify-items:center;gap:3px;scroll-snap-align:start;padding:9px 5px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text)}.weather-hour:hover{background:var(--surface-secondary)}.weather-hour[aria-pressed=true]{border:2px solid var(--accent);background:var(--hero)}.weather-hour-icon{font-size:21px;line-height:1.2}.weather-hour small{font-size:10px;color:var(--text-secondary)}.weather-hour-detail{border-top:1px solid var(--border);padding-top:10px;font-size:11px;color:var(--text-secondary);line-height:1.7}.weather-credit{margin-top:17px;border-top:1px solid var(--border);padding-top:9px;font-size:10px;color:var(--text-muted)}.weather-credit a{text-decoration:underline;text-underline-offset:2px}.weather-widget [hidden]{display:none}@media(max-width:760px){.weather-location .button,.weather-manual .button,.weather-hour{min-height:44px}.weather-current dl,.weather-summary dl{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(prefers-reduced-motion:reduce){.weather-hours{scroll-behavior:auto}}
|
||||
@@ -0,0 +1,132 @@
|
||||
(() => {
|
||||
const weather = code => {
|
||||
if (code === 0) return ['Clear sky', '☀'];
|
||||
if ([1, 2].includes(code)) return ['Partly cloudy', '⛅'];
|
||||
if (code === 3) return ['Overcast', '☁'];
|
||||
if ([45, 48].includes(code)) return ['Fog', '≋'];
|
||||
if ([51, 53, 55, 56, 57].includes(code)) return ['Drizzle', '☂'];
|
||||
if ([61, 63, 65, 66, 67, 80, 81, 82].includes(code)) return ['Rain', '☔'];
|
||||
if ([71, 73, 75, 77, 85, 86].includes(code)) return ['Snow', '❄'];
|
||||
if ([95, 96, 97, 99].includes(code)) return ['Thunderstorm', '⚡'];
|
||||
return ['Conditions unavailable', '○'];
|
||||
};
|
||||
const value = (number, unit = '', digits = 0) => number == null || !Number.isFinite(Number(number)) ? '—' : `${Number(number).toFixed(digits)}${unit}`;
|
||||
const clock = timestamp => typeof timestamp === 'string' && timestamp.includes('T') ? timestamp.split('T')[1].slice(0, 5) : '—';
|
||||
const day = timestamp => typeof timestamp === 'string' ? timestamp.slice(5, 10) : '';
|
||||
const csrf = () => decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '');
|
||||
function metric(list, label, content) {
|
||||
const item = document.createElement('div');
|
||||
const term = document.createElement('dt'); term.textContent = label;
|
||||
const definition = document.createElement('dd'); definition.textContent = content;
|
||||
item.append(term, definition); list.append(item);
|
||||
}
|
||||
function mount(card) {
|
||||
const root = card.querySelector('.weather-widget');
|
||||
if (!root) return () => {};
|
||||
const status = root.querySelector('[data-weather-status]');
|
||||
const content = root.querySelector('[data-weather-content]');
|
||||
const hours = root.querySelector('[data-hours]');
|
||||
const detail = root.querySelector('[data-hour-detail]');
|
||||
const toggle = root.querySelector('[data-hours-toggle]');
|
||||
const controller = new AbortController();
|
||||
let request = null;
|
||||
let forecast = null;
|
||||
let expanded = false;
|
||||
let selected = 0;
|
||||
function renderHour(index) {
|
||||
selected = index;
|
||||
const hourly = forecast.hourly;
|
||||
const parts = [
|
||||
`${day(hourly.time[index])} ${clock(hourly.time[index])} ${forecast.timezone}`,
|
||||
weather(hourly.weather_code?.[index])[0],
|
||||
`Temperature ${value(hourly.temperature_2m?.[index], '°C', 1)}`,
|
||||
`Feels like ${value(hourly.apparent_temperature?.[index], '°C', 1)}`,
|
||||
`Precipitation ${value(hourly.precipitation?.[index], ' mm', 1)}`,
|
||||
`Chance ${value(hourly.precipitation_probability?.[index], '%')}`,
|
||||
`Wind ${value(hourly.wind_speed_10m?.[index], ' km/h')}, gusts ${value(hourly.wind_gusts_10m?.[index], ' km/h')}, direction ${value(hourly.wind_direction_10m?.[index], '°')}`,
|
||||
`Humidity ${value(hourly.relative_humidity_2m?.[index], '%')}`,
|
||||
`Cloud ${value(hourly.cloud_cover?.[index], '%')}`,
|
||||
`UV ${value(hourly.uv_index?.[index], '', 1)}`,
|
||||
];
|
||||
detail.textContent = parts.join(' · ');
|
||||
hours.querySelectorAll('button').forEach(button => button.setAttribute('aria-pressed', String(Number(button.dataset.hour) === index)));
|
||||
}
|
||||
function renderHours() {
|
||||
hours.replaceChildren();
|
||||
const hourly = forecast.hourly;
|
||||
const limit = Math.min(hourly.time.length, expanded ? 48 : 24);
|
||||
for (let index = 0; index < limit; index++) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button'; button.className = 'weather-hour'; button.dataset.hour = index;
|
||||
button.setAttribute('aria-label', `${day(hourly.time[index])} ${clock(hourly.time[index])}, ${weather(hourly.weather_code?.[index])[0]}, ${value(hourly.temperature_2m?.[index], ' degrees Celsius')}, precipitation chance ${value(hourly.precipitation_probability?.[index], '%')}`);
|
||||
const icon = document.createElement('span'); icon.className = 'weather-hour-icon'; icon.setAttribute('aria-hidden', 'true'); icon.textContent = weather(hourly.weather_code?.[index])[1];
|
||||
const time = document.createElement('strong'); time.textContent = clock(hourly.time[index]);
|
||||
const temp = document.createElement('span'); temp.textContent = value(hourly.temperature_2m?.[index], '°');
|
||||
const rain = document.createElement('small'); rain.textContent = value(hourly.precipitation_probability?.[index], '% rain');
|
||||
button.append(time, icon, temp, rain); hours.append(button);
|
||||
}
|
||||
if (selected >= limit) selected = 0;
|
||||
if (limit) renderHour(selected);
|
||||
}
|
||||
function render(data) {
|
||||
forecast = data;
|
||||
content.hidden = false;
|
||||
const current = data.current, daily = data.daily;
|
||||
root.querySelector('[data-current-temp]').textContent = value(current.temperature_2m, '°C', 1);
|
||||
root.querySelector('[data-current-condition]').textContent = weather(current.weather_code)[0];
|
||||
root.querySelector('[data-current-feels]').textContent = `Feels like ${value(current.apparent_temperature, '°C', 1)}`;
|
||||
const currentDetails = root.querySelector('[data-current-details]'); currentDetails.replaceChildren();
|
||||
metric(currentDetails, 'Precipitation', value(current.precipitation, ' mm', 1));
|
||||
metric(currentDetails, 'Wind', `${value(current.wind_speed_10m, ' km/h')} · ${value(current.wind_direction_10m, '°')}`);
|
||||
metric(currentDetails, 'Humidity', value(current.relative_humidity_2m, '%'));
|
||||
metric(currentDetails, 'Cloud cover', value(current.cloud_cover, '%'));
|
||||
const summary = root.querySelector('[data-daily-summary]'); summary.replaceChildren();
|
||||
const first = key => daily[key]?.[0];
|
||||
metric(summary, 'High / low', `${value(first('temperature_2m_max'), '°C')} / ${value(first('temperature_2m_min'), '°C')}`);
|
||||
metric(summary, 'Sunrise / sunset', `${clock(first('sunrise'))} / ${clock(first('sunset'))}`);
|
||||
const daylight = first('daylight_duration');
|
||||
metric(summary, 'Daylight', daylight == null ? '—' : `${Math.floor(daylight / 3600)} h ${Math.round(daylight % 3600 / 60)} m`);
|
||||
metric(summary, 'Precipitation', `${value(first('precipitation_sum'), ' mm', 1)} · up to ${value(first('precipitation_probability_max'), '%')} chance`);
|
||||
metric(summary, 'Peak gust / UV', `${value(first('wind_gusts_10m_max'), ' km/h')} / ${value(first('uv_index_max'), '', 1)}`);
|
||||
if (Number(first('snowfall_sum')) > 0) metric(summary, 'Snowfall', value(first('snowfall_sum'), ' cm', 1));
|
||||
renderHours();
|
||||
root.querySelector('[data-weather-updated]').textContent = `Conditions valid ${clock(current.time)} ${data.timezone} · fetched ${new Date(data.fetched_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
|
||||
status.textContent = data.stale ? 'Showing cached forecast. Live refresh is unavailable.' : 'Forecast ready';
|
||||
status.classList.toggle('stale', data.stale);
|
||||
}
|
||||
async function load() {
|
||||
request?.abort();
|
||||
request = new AbortController();
|
||||
const location = window.DashboardLocation.get();
|
||||
root.querySelector('[data-location-name]').textContent = location.name;
|
||||
status.textContent = forecast ? 'Refreshing forecast…' : 'Loading forecast…';
|
||||
try {
|
||||
const response = await fetch(root.dataset.weatherUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf() }, body: JSON.stringify(location), signal: request.signal });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Forecast unavailable');
|
||||
render(data);
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
status.textContent = `${error.message}. ${forecast ? 'Showing the last loaded forecast.' : 'Try again later.'}`;
|
||||
status.classList.add('stale');
|
||||
content.hidden = !forecast;
|
||||
}
|
||||
}
|
||||
root.querySelector('[data-use-location]').addEventListener('click', async () => {
|
||||
status.textContent = 'Requesting browser location…';
|
||||
try { await window.DashboardLocation.locate(); } catch (error) { status.textContent = error.message; }
|
||||
}, { signal: controller.signal });
|
||||
root.querySelector('[data-weather-refresh]').addEventListener('click', load, { signal: controller.signal });
|
||||
root.querySelector('[data-manual-location]').addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
try { window.DashboardLocation.set(Object.fromEntries(new FormData(event.target))); } catch (error) { status.textContent = error.message; }
|
||||
}, { signal: controller.signal });
|
||||
toggle.addEventListener('click', () => { expanded = !expanded; toggle.setAttribute('aria-expanded', String(expanded)); toggle.textContent = expanded ? 'Show 24 hours' : 'Show 48 hours'; renderHours(); }, { signal: controller.signal });
|
||||
hours.addEventListener('click', event => { const button = event.target.closest('button[data-hour]'); if (button) renderHour(Number(button.dataset.hour)); }, { signal: controller.signal });
|
||||
const unsubscribe = window.DashboardLocation.subscribe(load);
|
||||
const timer = setInterval(load, 900000);
|
||||
load();
|
||||
return () => { controller.abort(); request?.abort(); clearInterval(timer); unsubscribe(); };
|
||||
}
|
||||
window.DashboardOpenMeteo = { mount };
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}">
|
||||
<div class="page-heading dashboard-heading"><div><div class="eyebrow"><span class="eyebrow-line"></span> YOUR WORKSPACE</div><h1>{{ title }}<span class="heading-period">.</span></h1><p>Make this space your own with a few useful widgets.</p></div><div class="dashboard-actions"><button class="button secondary" id="catalogue-toggle" type="button" aria-controls="widget-catalogue" aria-expanded="false" aria-label="Open widget catalogue"><i class="bi bi-gear"></i> Widgets</button><button class="button secondary" id="reset-layout" type="button" hidden>Reset</button><button class="button primary" id="edit-layout" type="button">Edit layout</button></div></div>
|
||||
<div id="layout-status" class="layout-status" role="status" aria-live="polite">Layout saved</div>
|
||||
<div class="dashboard-pages" aria-label="Dashboard pages"><a href="{% url 'dashboard:index' %}" {% if dashboard_page == 'overview' %}aria-current="page"{% endif %}>Overview</a><a href="{% url 'dashboard:page' 'personal' %}" {% if dashboard_page == 'personal' %}aria-current="page"{% endif %}>Personal</a></div>
|
||||
<div id="widget-grid" class="widget-grid" data-page="{{ dashboard_page }}" data-revision="{{ layout.revision }}" data-save-url="{% url 'dashboard:layout' dashboard_page %}">
|
||||
{% for instance in instances %}{% include 'dashboard/widget_card.html' %}{% endfor %}
|
||||
</div>
|
||||
<p id="empty-layout" class="empty-layout" {% if instances %}hidden{% endif %}>This page is empty. Choose <strong>Edit layout</strong>, then add a widget.</p>
|
||||
<template id="open-meteo-widget-template">{% include 'dashboard/widgets/open_meteo.html' %}</template>
|
||||
<template id="buienradar-widget-template">{% include 'dashboard/widgets/buienradar.html' %}</template>
|
||||
<aside id="widget-catalogue" class="widget-catalogue" aria-label="Widget catalogue" aria-hidden="true" inert><div class="catalogue-head"><div><span class="eyebrow">BUILD YOUR PAGE</span><h2>Widgets</h2></div><button type="button" id="catalogue-close" class="button ghost" aria-label="Close widget catalogue"><i class="bi bi-x-lg"></i></button></div><label for="widget-search">Search widgets</label><input id="widget-search" type="search" placeholder="Search by name or description"><div class="catalogue-list">{% for widget in catalogue %}<div class="catalogue-entry" draggable="true" data-widget-type="{{ widget.id }}" data-title="{{ widget.title|lower }}" data-description="{{ widget.description|lower }}"><i class="bi {{ widget.icon }}" aria-hidden="true"></i><div><strong>{{ widget.title }}</strong><small>{{ widget.description }}</small></div><button type="button" class="button secondary" data-add="{{ widget.id }}">Add</button></div>{% endfor %}</div><p class="catalogue-hint">Drag onto a dashed slot, or use Add and the Move controls. Changes save when you select Done.</p></aside><div id="catalogue-backdrop" class="catalogue-backdrop" hidden></div>
|
||||
{{ catalogue|length|json_script:"widget-count" }}
|
||||
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/builder.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1 @@
|
||||
<article class="widget-card content-card" data-widget-platform="bottom" data-instance-id="{{ instance.id }}" data-widget-type="{{ instance.type }}" data-span="{{ instance.span }}"><header class="widget-card-head"><div><i class="bi {{ instance.kind.icon }}" aria-hidden="true"></i><h2>{{ instance.kind.title }}</h2></div><div class="widget-controls"><button type="button" data-move="left" aria-label="Move {{ instance.kind.title }} earlier" title="Move earlier">←</button><button type="button" data-move="right" aria-label="Move {{ instance.kind.title }} later" title="Move later">→</button><button type="button" data-span-toggle aria-label="Resize {{ instance.kind.title }}" title="Resize">↔</button><button type="button" data-settings-toggle aria-label="Settings for {{ instance.kind.title }}" title="Settings"><i class="bi bi-sliders"></i></button><button type="button" data-remove aria-label="Remove {{ instance.kind.title }}" title="Remove"><i class="bi bi-x-lg"></i></button><span class="drag-handle" draggable="true" aria-hidden="true"><i class="bi bi-grip-vertical"></i></span></div></header><div class="widget-body">{% include instance.kind.template %}</div><div class="widget-settings" hidden>{% if instance.type == 'notes' %}<label>Note text <textarea data-setting="text" maxlength="1000">{{ instance.settings.text|default:'' }}</textarea></label>{% else %}<p>No settings for this widget.</p>{% endif %}</div></article>
|
||||
@@ -0,0 +1,8 @@
|
||||
<section class="rain-widget" data-rain-url="{% url 'dashboard:buienradar' %}" aria-label="Buienradar rain radar">
|
||||
<div class="rain-location"><div><strong data-rain-location>Heerenveen</strong><small data-rain-updated>Waiting for rain forecast</small></div><div><button type="button" class="button secondary" data-rain-geolocate>Use my location</button><button type="button" class="button ghost" data-rain-refresh>Refresh</button></div></div>
|
||||
<details class="rain-manual"><summary>Choose coordinates manually</summary><form data-rain-manual><label>Latitude <input name="latitude" type="number" min="-90" max="90" step="any" required placeholder="52.96"></label><label>Longitude <input name="longitude" type="number" min="-180" max="180" step="any" required placeholder="5.92"></label><button class="button secondary" type="submit">Use coordinates</button></form><p>Shared with weather widgets on this page. Coordinates are not saved.</p></details>
|
||||
<div class="rain-layout"><div class="rain-radar"><div class="rain-radar-heading"><h3>Netherlands radar</h3><span>Latest image</span></div><div class="rain-radar-frame"><img data-rain-image src="https://image.buienradar.nl/2.0/image/single/RadarMapRainNL?height=512&width=500&renderBackground=True&renderBranding=True&renderText=True" width="500" height="512" alt="Latest Buienradar rain radar image of the Netherlands. Location is not marked."><iframe data-rain-animation title="Buienradar official animated radar gadget" width="256" height="406" loading="lazy" hidden></iframe></div><div class="rain-radar-actions"><button type="button" class="button secondary" data-rain-play aria-pressed="false">Play animation</button><button type="button" class="button ghost" data-rain-fullscreen>Full screen</button></div><p class="rain-caveat">Animation is managed by Buienradar. Frame times and seeking are not available from this embed.</p></div>
|
||||
<div class="rain-forecast"><div class="rain-forecast-heading"><h3>Rain at this location</h3><span>Forecast · next 2 hours</span></div><p class="rain-status" data-rain-status role="status" aria-live="polite">Loading rain forecast…</p><div data-rain-content hidden><div class="rain-reading"><strong data-rain-class>—</strong><span data-rain-amount>—</span><small data-rain-time>—</small></div><div class="rain-bars" data-rain-bars aria-hidden="true"></div><label class="rain-scrubber-label" for="rain-scrubber-{{ instance.id|default:'template' }}">Choose forecast time</label><input id="rain-scrubber-{{ instance.id|default:'template' }}" data-rain-slider type="range" min="0" max="0" value="0" aria-label="Forecast time"><div class="rain-step-actions"><button type="button" class="button ghost" data-rain-prev>Previous forecast time</button><button type="button" class="button ghost" data-rain-next>Next forecast time</button></div></div><p class="rain-caveat">Forecast values are separate from the radar image; their times are not synchronized.</p></div></div>
|
||||
<dialog class="rain-dialog" data-rain-dialog aria-label="Buienradar full screen"><div class="rain-dialog-head"><strong>Buienradar · Netherlands</strong><button type="button" class="button secondary" data-rain-close>Close</button></div><img data-rain-dialog-image src="https://image.buienradar.nl/2.0/image/single/RadarMapRainNL?height=512&width=500&renderBackground=True&renderBranding=True&renderText=True" width="500" height="512" alt="Latest Buienradar rain radar image of the Netherlands. Location is not marked."><iframe data-rain-dialog-animation title="Buienradar official animated radar gadget in full screen" width="256" height="406" loading="lazy" hidden></iframe></dialog>
|
||||
<footer class="rain-credit">Radar and precipitation data: <a href="https://www.buienradar.nl/" target="_blank" rel="noopener noreferrer">Buienradar.nl</a> · Rain intensity categories adapted for display.</footer>
|
||||
</section>
|
||||
@@ -0,0 +1 @@
|
||||
<p class="note-preview">{{ instance.settings.text|default:'Add a note in widget settings.' }}</p>
|
||||
@@ -0,0 +1,10 @@
|
||||
<section class="weather-widget" data-weather-url="{% url 'dashboard:open_meteo' %}" aria-label="Open-Meteo forecast">
|
||||
<div class="weather-location"><div><strong data-location-name>Heerenveen</strong><small data-weather-updated>Waiting for forecast</small></div><div><button class="button secondary" type="button" data-use-location>Use my location</button><button class="button ghost" type="button" data-weather-refresh>Refresh</button></div></div>
|
||||
<details class="weather-manual"><summary>Choose coordinates manually</summary><form data-manual-location><label>Latitude <input name="latitude" type="number" min="-90" max="90" step="any" required placeholder="52.96"></label><label>Longitude <input name="longitude" type="number" min="-180" max="180" step="any" required placeholder="5.92"></label><button class="button secondary" type="submit">Use coordinates</button></form><p>Coordinates stay in this browser session and are rounded before the weather request.</p></details>
|
||||
<p class="weather-status" data-weather-status role="status" aria-live="polite">Loading forecast…</p>
|
||||
<div data-weather-content hidden><div class="weather-current"><div><span class="weather-temperature" data-current-temp></span><strong data-current-condition></strong><small data-current-feels></small></div><dl data-current-details></dl></div>
|
||||
<div class="weather-summary"><h3>Today</h3><dl data-daily-summary></dl></div>
|
||||
<div class="weather-hours-heading"><h3>Hourly forecast</h3><button class="button ghost" type="button" data-hours-toggle aria-expanded="false">Show 48 hours</button></div><div class="weather-hours" data-hours role="group" aria-label="Hourly forecast"></div><div class="weather-hour-detail" data-hour-detail aria-live="polite"></div>
|
||||
</div>
|
||||
<footer class="weather-credit">Weather data: <a href="https://open-meteo.com/" target="_blank" rel="noopener noreferrer">Open-Meteo</a> · Forecast data adapted for display · <a href="https://open-meteo.com/en/licence" target="_blank" rel="noopener noreferrer">CC BY 4.0</a></footer>
|
||||
</section>
|
||||
@@ -0,0 +1 @@
|
||||
<nav class="widget-shortcuts" aria-label="Quick links"><a href="{% url 'projects:list' %}">Projects <i class="bi bi-arrow-up-right"></i></a><a href="{% url 'today' %}">Design examples <i class="bi bi-arrow-up-right"></i></a></nav>
|
||||
@@ -0,0 +1 @@
|
||||
<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>
|
||||
@@ -0,0 +1,138 @@
|
||||
import json
|
||||
import uuid
|
||||
import hashlib
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.cache import caches
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import DashboardLayout
|
||||
from .views import validate_widgets
|
||||
from .weather import ForecastUnavailable, coordinates, get_forecast
|
||||
from .buienradar import RainUnavailable, get_rain, parse_forecast
|
||||
|
||||
|
||||
class DashboardTests(TestCase):
|
||||
def setUp(self):
|
||||
self.one = get_user_model().objects.create_user(username="one", password="password")
|
||||
self.two = get_user_model().objects.create_user(username="two", password="password")
|
||||
|
||||
def test_registry_rejects_duplicate_single_instance(self):
|
||||
item = {"id": str(uuid.uuid4()), "type": "welcome", "span": 2, "settings": {}, "visible": True}
|
||||
with self.assertRaises(ValueError):
|
||||
validate_widgets([item, {**item, "id": str(uuid.uuid4())}])
|
||||
|
||||
def test_user_and_page_layouts_are_independent(self):
|
||||
self.client.force_login(self.one)
|
||||
self.client.get(reverse("dashboard:index"))
|
||||
self.client.get(reverse("dashboard:page", args=["personal"]))
|
||||
self.client.force_login(self.two)
|
||||
self.client.get(reverse("dashboard:index"))
|
||||
self.assertEqual(DashboardLayout.objects.count(), 3)
|
||||
ids = [widget["id"] for layout in DashboardLayout.objects.all() for widget in layout.widgets]
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
|
||||
def test_layout_update_is_scoped_to_authenticated_user(self):
|
||||
self.client.force_login(self.one)
|
||||
self.client.get(reverse("dashboard:index"))
|
||||
original = DashboardLayout.objects.get(user=self.one, page="overview")
|
||||
self.client.force_login(self.two)
|
||||
response = self.client.put(
|
||||
reverse("dashboard:layout", args=["overview"]),
|
||||
json.dumps({"revision": 0, "widgets": []}),
|
||||
content_type="application/json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
original.refresh_from_db()
|
||||
self.assertEqual(original.revision, 0)
|
||||
self.assertEqual(len(original.widgets), 2)
|
||||
|
||||
def test_reorder_persists_and_revision_conflict(self):
|
||||
self.client.force_login(self.one)
|
||||
self.client.get(reverse("dashboard:index"))
|
||||
layout = DashboardLayout.objects.get(user=self.one, page="overview")
|
||||
widgets = list(reversed(layout.widgets))
|
||||
url = reverse("dashboard:layout", args=["overview"])
|
||||
response = self.client.put(url, json.dumps({"revision": 0, "widgets": widgets}), content_type="application/json")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
layout.refresh_from_db()
|
||||
self.assertEqual([item["type"] for item in layout.widgets], ["shortcuts", "welcome"])
|
||||
self.assertEqual(self.client.put(url, json.dumps({"revision": 0, "widgets": widgets}), content_type="application/json").status_code, 409)
|
||||
|
||||
def test_open_meteo_registry_and_authenticated_endpoint(self):
|
||||
self.assertEqual(self.client.post(reverse("dashboard:open_meteo"), data="{}", content_type="application/json").status_code, 302)
|
||||
self.client.force_login(self.one)
|
||||
with patch("dashboard.views.get_forecast", return_value={"current": {}, "hourly": {}, "daily": {}, "stale": False}):
|
||||
response = self.client.post(reverse("dashboard:open_meteo"), json.dumps({"latitude": 52.96, "longitude": 5.92}), content_type="application/json")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn("open_meteo", __import__("dashboard.registry", fromlist=["WIDGETS"]).WIDGETS)
|
||||
|
||||
def test_weather_coordinate_validation_and_shared_cache(self):
|
||||
with self.assertRaises(ValueError):
|
||||
coordinates("nan", 5)
|
||||
caches["weather"].clear()
|
||||
payload = {"current": {"temperature_2m": 10}, "hourly": {"time": ["2026-10-14T12:00"]}, "daily": {}, "fetched_at": "2026-10-14T10:00:00+00:00"}
|
||||
with patch("dashboard.weather.request_forecast", return_value=payload) as fetch:
|
||||
first = get_forecast(52.961, 5.919)
|
||||
second = get_forecast(52.96, 5.92)
|
||||
self.assertFalse(first["stale"])
|
||||
self.assertEqual(second["current"]["temperature_2m"], 10)
|
||||
fetch.assert_called_once()
|
||||
caches["weather"].clear()
|
||||
|
||||
def test_weather_provider_failure_is_isolated(self):
|
||||
self.client.force_login(self.one)
|
||||
with patch("dashboard.views.get_forecast", side_effect=ForecastUnavailable("Weather service is temporarily unavailable")):
|
||||
response = self.client.post(reverse("dashboard:open_meteo"), json.dumps({"latitude": 52.96, "longitude": 5.92}), content_type="application/json")
|
||||
self.assertEqual(response.status_code, 503)
|
||||
|
||||
def test_weather_stale_cache_is_labeled_after_provider_failure(self):
|
||||
cache = caches["weather"]
|
||||
cache.clear()
|
||||
key = hashlib.sha256(b"open-meteo:v1:52.96:5.92").hexdigest()
|
||||
cache.set(f"stale:{key}", {"current": {"temperature_2m": 8}, "hourly": {"time": ["2026-10-14T12:00"]}, "daily": {}, "fetched_at": "2026-10-14T10:00:00+00:00"}, 60)
|
||||
with patch("dashboard.weather.request_forecast", side_effect=OSError("provider offline")):
|
||||
result = get_forecast(52.96, 5.92)
|
||||
self.assertTrue(result["stale"])
|
||||
self.assertEqual(result["current"]["temperature_2m"], 8)
|
||||
cache.clear()
|
||||
|
||||
def test_buienradar_feed_parsing_crosses_midnight(self):
|
||||
now = datetime(2026, 10, 14, 23, 54, tzinfo=ZoneInfo("Europe/Amsterdam"))
|
||||
points = parse_forecast("000|23:55\n077|00:00\n125|00:05\n", now=now)
|
||||
self.assertEqual(points[0]["label"], "None")
|
||||
self.assertAlmostEqual(points[1]["mm_per_hour"], 0.1)
|
||||
self.assertEqual(points[1]["time"][:10], "2026-10-15")
|
||||
self.assertEqual(points[2]["label"], "Moderate")
|
||||
self.assertIsNone(parse_forecast("255|23:55\n", now=now)[0]["mm_per_hour"])
|
||||
with self.assertRaises(RainUnavailable):
|
||||
parse_forecast("not a feed", now=now)
|
||||
|
||||
def test_buienradar_endpoint_auth_range_and_cache(self):
|
||||
url = reverse("dashboard:buienradar")
|
||||
self.assertEqual(self.client.post(url, data="{}", content_type="application/json").status_code, 302)
|
||||
self.client.force_login(self.one)
|
||||
self.assertEqual(self.client.post(url, json.dumps({"latitude": 40, "longitude": 5}), content_type="application/json").status_code, 400)
|
||||
caches["weather"].clear()
|
||||
payload = {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}
|
||||
with patch("dashboard.buienradar.request_rain", return_value=payload) as fetch:
|
||||
first = get_rain(52.961, 5.919)
|
||||
second = get_rain(52.96, 5.92)
|
||||
self.assertFalse(first["stale"])
|
||||
self.assertEqual(second["points"], first["points"])
|
||||
fetch.assert_called_once()
|
||||
caches["weather"].clear()
|
||||
|
||||
def test_buienradar_stale_fallback(self):
|
||||
cache = caches["weather"]
|
||||
cache.clear()
|
||||
key = hashlib.sha256(b"buienradar:v1:52.96:5.92").hexdigest()
|
||||
cache.set(f"stale:{key}", {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}, 60)
|
||||
with patch("dashboard.buienradar.request_rain", side_effect=OSError("offline")):
|
||||
result = get_rain(52.96, 5.92)
|
||||
self.assertTrue(result["stale"])
|
||||
cache.clear()
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = "dashboard"
|
||||
urlpatterns = [
|
||||
path("", views.index, name="index"),
|
||||
path("dashboard/<slug:page>/", views.page, name="page"),
|
||||
path("dashboard/<slug:page>/layout/", views.layout_api, name="layout"),
|
||||
path("dashboard/weather/open-meteo/", views.open_meteo_api, name="open_meteo"),
|
||||
path("dashboard/weather/buienradar/", views.buienradar_api, name="buienradar"),
|
||||
]
|
||||
@@ -0,0 +1,122 @@
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.views.decorators.csrf import ensure_csrf_cookie
|
||||
|
||||
from .models import DashboardLayout
|
||||
from .registry import WIDGETS
|
||||
from .weather import ForecastUnavailable, get_forecast
|
||||
from .buienradar import RainUnavailable, get_rain
|
||||
|
||||
PAGES = {"overview": "Overview", "personal": "Personal"}
|
||||
|
||||
def default_widgets():
|
||||
return [
|
||||
{"id": str(uuid.uuid4()), "type": "welcome", "order": 0, "span": 2, "settings": {}, "visible": True},
|
||||
{"id": str(uuid.uuid4()), "type": "shortcuts", "order": 1, "span": 1, "settings": {}, "visible": True},
|
||||
]
|
||||
|
||||
|
||||
def validate_widgets(items):
|
||||
if not isinstance(items, list) or len(items) > 40:
|
||||
raise ValueError("Invalid widget list")
|
||||
seen_ids, seen_types, cleaned = set(), set(), []
|
||||
for order, item in enumerate(items):
|
||||
if not isinstance(item, dict) or item.get("type") not in WIDGETS:
|
||||
raise ValueError("Unknown widget type")
|
||||
kind = WIDGETS[item["type"]]
|
||||
try:
|
||||
identifier = str(uuid.UUID(item["id"]))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise ValueError("Invalid widget ID") from None
|
||||
if identifier in seen_ids or (not kind.multiple and kind.id in seen_types):
|
||||
raise ValueError("Duplicate widget")
|
||||
span = item.get("span")
|
||||
settings = item.get("settings", {})
|
||||
if type(span) is not int or span not in (1, 2) or not isinstance(settings, dict) or set(settings) - set(kind.settings_keys):
|
||||
raise ValueError("Invalid widget settings or span")
|
||||
if any(not isinstance(value, str) or len(value) > 1000 for value in settings.values()):
|
||||
raise ValueError("Invalid widget setting value")
|
||||
if type(item.get("visible")) is not bool:
|
||||
raise ValueError("Invalid visibility")
|
||||
seen_ids.add(identifier)
|
||||
seen_types.add(kind.id)
|
||||
cleaned.append({"id": identifier, "type": kind.id, "order": order, "span": span, "settings": settings, "visible": item["visible"]})
|
||||
return cleaned
|
||||
|
||||
|
||||
def render_page(request, page):
|
||||
if page not in PAGES:
|
||||
return JsonResponse({"error": "Unknown dashboard page"}, status=404)
|
||||
layout, _ = DashboardLayout.objects.get_or_create(user=request.user, page=page, defaults={"widgets": default_widgets()})
|
||||
instances = [{**item, "kind": WIDGETS[item["type"]]} for item in layout.widgets if item["type"] in WIDGETS and item.get("visible", True)]
|
||||
return render(request, "dashboard/index.html", {"title": PAGES[page], "section": "dashboard", "dashboard_page": page, "layout": layout, "instances": instances, "catalogue": WIDGETS.values()})
|
||||
|
||||
|
||||
@login_required
|
||||
@ensure_csrf_cookie
|
||||
def index(request):
|
||||
return render_page(request, "overview")
|
||||
|
||||
|
||||
@login_required
|
||||
@ensure_csrf_cookie
|
||||
def page(request, page):
|
||||
return render_page(request, page)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["PUT"])
|
||||
def layout_api(request, page):
|
||||
if page not in PAGES:
|
||||
return JsonResponse({"error": "Unknown dashboard page"}, status=404)
|
||||
try:
|
||||
body = json.loads(request.body)
|
||||
if not isinstance(body, dict) or type(body.get("revision")) is not int:
|
||||
raise ValueError("Invalid revision")
|
||||
widgets = validate_widgets(body.get("widgets"))
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
return JsonResponse({"error": str(exc)}, status=400)
|
||||
with transaction.atomic():
|
||||
layout = DashboardLayout.objects.select_for_update().get_or_create(user=request.user, page=page, defaults={"widgets": default_widgets()})[0]
|
||||
if layout.revision != body["revision"]:
|
||||
return JsonResponse({"error": "Layout changed in another tab. Reload before saving.", "revision": layout.revision}, status=409)
|
||||
layout.widgets = widgets
|
||||
layout.revision += 1
|
||||
layout.save(update_fields=["widgets", "revision", "updated_at"])
|
||||
return JsonResponse({"revision": layout.revision, "widgets": widgets})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["POST"])
|
||||
def open_meteo_api(request):
|
||||
try:
|
||||
body = json.loads(request.body)
|
||||
if not isinstance(body, dict):
|
||||
raise ValueError("Invalid location")
|
||||
forecast = get_forecast(body.get("latitude"), body.get("longitude"))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return JsonResponse({"error": "Choose a valid location"}, status=400)
|
||||
except ForecastUnavailable as exc:
|
||||
return JsonResponse({"error": str(exc)}, status=503)
|
||||
return JsonResponse(forecast)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["POST"])
|
||||
def buienradar_api(request):
|
||||
try:
|
||||
body = json.loads(request.body)
|
||||
if not isinstance(body, dict):
|
||||
raise ValueError("Invalid location")
|
||||
rain = get_rain(body.get("latitude"), body.get("longitude"))
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
return JsonResponse({"error": str(exc) or "Choose a valid location"}, status=400)
|
||||
except RainUnavailable as exc:
|
||||
return JsonResponse({"error": str(exc)}, status=503)
|
||||
return JsonResponse(rain)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Open-Meteo adapter. No user location is persisted or logged."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from django.core.cache import caches
|
||||
|
||||
ENDPOINT = "https://api.open-meteo.com/v1/forecast"
|
||||
CURRENT = (
|
||||
"temperature_2m", "apparent_temperature", "relative_humidity_2m", "weather_code",
|
||||
"precipitation", "wind_speed_10m", "wind_direction_10m", "cloud_cover", "is_day",
|
||||
)
|
||||
HOURLY = (
|
||||
"temperature_2m", "apparent_temperature", "precipitation", "precipitation_probability",
|
||||
"wind_speed_10m", "wind_gusts_10m", "wind_direction_10m", "relative_humidity_2m",
|
||||
"cloud_cover", "uv_index", "weather_code", "is_day",
|
||||
)
|
||||
DAILY = (
|
||||
"temperature_2m_max", "temperature_2m_min", "sunrise", "sunset", "daylight_duration",
|
||||
"precipitation_sum", "precipitation_probability_max", "wind_gusts_10m_max", "uv_index_max", "snowfall_sum",
|
||||
)
|
||||
FRESH_SECONDS = 900
|
||||
STALE_SECONDS = 3600
|
||||
|
||||
|
||||
class ForecastUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def coordinates(latitude, longitude):
|
||||
try:
|
||||
lat, lon = float(latitude), float(longitude)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("Invalid coordinates") from None
|
||||
if not math.isfinite(lat) or not math.isfinite(lon) or not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
|
||||
raise ValueError("Invalid coordinates")
|
||||
return round(lat, 2), round(lon, 2)
|
||||
|
||||
|
||||
def request_forecast(lat, lon):
|
||||
params = {
|
||||
"latitude": lat, "longitude": lon, "timezone": "auto", "forecast_hours": 48,
|
||||
"forecast_days": 2, "temperature_unit": "celsius", "wind_speed_unit": "kmh",
|
||||
"precipitation_unit": "mm", "current": ",".join(CURRENT),
|
||||
"hourly": ",".join(HOURLY), "daily": ",".join(DAILY),
|
||||
}
|
||||
request = Request(f"{ENDPOINT}?{urlencode(params)}", headers={"User-Agent": "CommonGroundDashboard/1.0"})
|
||||
with urlopen(request, timeout=8) as response:
|
||||
if response.status != 200:
|
||||
raise ForecastUnavailable("Weather service is temporarily unavailable")
|
||||
payload = json.load(response)
|
||||
if payload.get("error") or not all(isinstance(payload.get(key), dict) for key in ("current", "hourly", "daily")):
|
||||
raise ForecastUnavailable("Weather data could not be read")
|
||||
if not isinstance(payload["hourly"].get("time"), list) or not payload["hourly"]["time"]:
|
||||
raise ForecastUnavailable("Hourly forecast is unavailable")
|
||||
return {
|
||||
"current": payload["current"], "hourly": payload["hourly"], "daily": payload["daily"],
|
||||
"timezone": payload.get("timezone_abbreviation") or payload.get("timezone") or "local time",
|
||||
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def get_forecast(latitude, longitude):
|
||||
lat, lon = coordinates(latitude, longitude)
|
||||
key = hashlib.sha256(f"open-meteo:v1:{lat:.2f}:{lon:.2f}".encode()).hexdigest()
|
||||
cache = caches["weather"]
|
||||
fresh = cache.get(f"fresh:{key}")
|
||||
if fresh is not None:
|
||||
return {**fresh, "stale": False}
|
||||
stale = cache.get(f"stale:{key}")
|
||||
lock = f"lock:{key}"
|
||||
if not cache.add(lock, True, timeout=20):
|
||||
if stale is not None:
|
||||
return {**stale, "stale": True}
|
||||
raise ForecastUnavailable("Forecast is being refreshed. Try again shortly")
|
||||
try:
|
||||
payload = request_forecast(lat, lon)
|
||||
cache.set(f"fresh:{key}", payload, timeout=FRESH_SECONDS)
|
||||
cache.set(f"stale:{key}", payload, timeout=STALE_SECONDS)
|
||||
return {**payload, "stale": False}
|
||||
except (OSError, ValueError, json.JSONDecodeError, ForecastUnavailable) as exc:
|
||||
if stale is not None:
|
||||
return {**stale, "stale": True}
|
||||
raise ForecastUnavailable("Weather service is temporarily unavailable") from exc
|
||||
finally:
|
||||
cache.delete(lock)
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=Common Ground Django dashboard and OAuth server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/home/jorenmartijn/Desktop/django_dashboard
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
EnvironmentFile=-%h/.config/common-ground/env
|
||||
ExecStart=/home/jorenmartijn/Desktop/django_dashboard/.venv-host/bin/python manage.py runserver 127.0.0.1:8765 --noreload
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Common Ground authenticated MCP server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/home/jorenmartijn/Desktop/django_dashboard
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=MCP_PUBLIC_URL=https://projects.jorendegraaf.eu/mcp
|
||||
Environment=OAUTH_ISSUER_URL=https://projects.jorendegraaf.eu
|
||||
EnvironmentFile=-%h/.config/common-ground/env
|
||||
ExecStart=/home/jorenmartijn/Desktop/django_dashboard/.venv-host/bin/python -m uvicorn mcp_server.server:app --host 100.91.62.59 --port 8766
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,21 @@
|
||||
# Buienradar widget
|
||||
|
||||
Verified 14 October 2026 against Buienradar's [Gratis Weerdata](https://www.buienradar.nl/overbuienradar/gratis-weerdata) page and live endpoint responses.
|
||||
|
||||
## Setup
|
||||
|
||||
**No API key or account is needed** for the documented free-data feed and embeds used here. Add **Rain radar** from the dashboard widget catalogue. It starts with Heerenveen; select **Use my location** or enter coordinates manually. The local forecast covers locations in the Netherlands.
|
||||
|
||||
Buienradar says its free data may be used for qualifying non-commercial websites or intranets with a visible `Buienradar.nl` source link. Mobile applications and commercial use require provider permission. This dashboard is an authenticated internal website, not a mobile app. Recheck terms or obtain permission before commercial or public use.
|
||||
|
||||
## Sources and behavior
|
||||
|
||||
- Local two-hour forecast: `https://gps.buienradar.nl/getrr.php?lat=…&lon=…`, documented on the free-data page. It returns rain codes at five-minute timestamps. The adapter uses Buienradar's documented formula `10^((value-109)/32)` to convert nonzero codes to mm/h. Zero means dry. At saturated high codes, the UI shows heavy rain without an exact mm/h estimate. The **None / Light / Moderate / Heavy** bands are presentation categories chosen by this project, not provider labels.
|
||||
- Radar snapshot: Buienradar's documented `https://image.buienradar.nl/2.0/image/single/RadarMapRainNL` embed, with branding and text enabled. The widget also uses its official `https://gadgets.buienradar.nl/gadget/radarfivedays` iframe for animation after the user presses Play. The iframe manages its own frames. Pause switches back to the latest static image; it does not freeze a particular frame. Full screen opens a local dialog, or the Buienradar site where dialogs are unavailable.
|
||||
- No radar frame URLs are extracted, proxied, stored, or synchronized to forecast values. The official embed does not provide frame timestamps or seek controls to this application. The slider and Previous/Next buttons move through **forecast** points only. The UI labels this distinction.
|
||||
- The Django forecast adapter shares a file cache among server workers: five-minute fresh interval, up-to-15-minute stale fallback, and a short lock to avoid duplicate upstream requests. It sends rounded coordinates to the provider. Browser coordinates stay in page memory and are submitted to Django via authenticated CSRF-protected POST; they are not saved in widget settings. The radar image and gadget are loaded directly from Buienradar, so the provider sees the browser's IP address.
|
||||
- The radar image has no reliable user-location marker or frame timestamp, so neither is claimed. The forecast source is separate from the weather model in the Open-Meteo widget; the two may differ.
|
||||
|
||||
## Attribution and limits
|
||||
|
||||
The widget displays a visible link to [Buienradar.nl](https://www.buienradar.nl/). The free-data page says radar images update about every five minutes; no numerical request quota was published there. The implementation refreshes the local forecast every five minutes while mounted. Availability and forecasts are not guaranteed. Recheck the source page before public or commercial deployment.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Open-Meteo widget
|
||||
|
||||
Verified 14 October 2026 against the [Forecast API documentation](https://open-meteo.com/en/docs), [terms](https://open-meteo.com/en/terms), [pricing](https://open-meteo.com/en/pricing), and [licence page](https://open-meteo.com/en/licence).
|
||||
|
||||
## Source and use
|
||||
|
||||
- Endpoint: `https://api.open-meteo.com/v1/forecast`. The adapter requests current, 48 hourly, and two daily periods with `timezone=auto`, Celsius, km/h and millimetres. It uses Open-Meteo's default Best Match models. The browser calls only the authenticated Django endpoint; it never calls Open-Meteo directly.
|
||||
- The free API is for non-commercial use, without an API key. The published limits are under 10,000 weighted calls/day, 5,000/hour, 600/minute, and 300,000/month. Requests with more than ten variables may count as multiple calls. This internal personal dashboard is intended for non-commercial use. Recheck eligibility and use a commercial plan before commercial or advertising-supported deployment.
|
||||
- The weather card visibly credits and links Open-Meteo and the CC BY 4.0 licence, and notes that forecast data is adapted for display. Best Match can combine models; confirm any additional model attribution requirements before broad publication.
|
||||
- Cached forecasts are shared between server workers via a file-based cache. Fresh data lasts 15 minutes; a failed refresh may show the last forecast for up to one hour with an explicit stale label. A short cache lock limits duplicate upstream requests. The UI refreshes every 15 minutes while mounted.
|
||||
- Browser location is requested only after clicking **Use my location**. A denial is remembered for the current page session to avoid repeated prompts. Manual coordinates and Heerenveen fallback are available. Coordinates are rounded to two decimals before the server request, sent in a POST body, and not stored in layout settings or browser storage. The cache key is a hash of rounded coordinates. No location is written to application logs by this adapter. Open-Meteo may log request URLs containing rounded coordinates under its own privacy policy.
|
||||
|
||||
## Display and limits
|
||||
|
||||
- Current conditions are Open-Meteo model data, not a local instrument reading. Precipitation periods and forecast probabilities follow the API definitions. Hourly detail is selectable by mouse, touch, and keyboard; 24 hours display initially, expandable to 48.
|
||||
- API errors do not affect other widgets. If no prior data is available, the card shows an error without inventing conditions. If older data is available, it stays visible with a stale warning.
|
||||
- Forecasts are estimates; accuracy and uptime are not guaranteed. Recheck provider terms and dataset attribution before public deployment.
|
||||
@@ -1,6 +1,7 @@
|
||||
from django import forms
|
||||
from .models import Card, Column, Profile, Project, Tag, Membership
|
||||
from django.contrib.auth import get_user_model
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
|
||||
class ProjectForm(forms.ModelForm):
|
||||
@@ -62,3 +63,11 @@ class ProfileForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Profile
|
||||
fields = ['display_name', 'avatar_url', 'timezone', 'language', 'theme']
|
||||
|
||||
def clean_timezone(self):
|
||||
value = self.cleaned_data['timezone'].strip()
|
||||
try:
|
||||
ZoneInfo(value)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
raise forms.ValidationError('Enter a valid IANA timezone, such as Europe/Amsterdam.')
|
||||
return value
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from .models import Profile
|
||||
|
||||
|
||||
class ProfileTimezoneMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
if request.user.is_authenticated:
|
||||
name = Profile.objects.filter(user=request.user).values_list('timezone', flat=True).first()
|
||||
if name:
|
||||
try:
|
||||
timezone.activate(ZoneInfo(name))
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
timezone.deactivate()
|
||||
else:
|
||||
timezone.deactivate()
|
||||
else:
|
||||
timezone.deactivate()
|
||||
try:
|
||||
return self.get_response(request)
|
||||
finally:
|
||||
timezone.deactivate()
|
||||
@@ -1,12 +1,13 @@
|
||||
{% extends 'core/base.html' %}
|
||||
{% block content %}
|
||||
<style>.htmx-indicator{display:none}.htmx-request.htmx-indicator,.htmx-request .htmx-indicator{display:inline}</style>
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<div><a href="{% url 'projects:list' %}">All projects</a><h1>{{ project.name }}</h1><p>{{ project.description }}</p>{% if project.git_repository_url %}<a href="{{ project.git_repository_url }}" rel="noopener noreferrer">Repository</a>{% endif %}<p>{{ done_count }} of {{ total_count }} cards done</p></div>
|
||||
{% if can_edit %}<div><a class="btn btn-outline-secondary" href="{% url 'projects:edit' project.id %}">Edit project</a> {% if project.archived %}<form class="d-inline" method="post" action="{% url 'projects:restore' project.id %}">{% csrf_token %}<button class="btn btn-outline-success">Restore project</button></form>{% else %}<form class="d-inline" method="post" action="{% url 'projects:archive' project.id %}">{% csrf_token %}<button class="btn btn-outline-danger">Archive project</button></form> <a class="btn btn-success" href="{% url 'projects:card_create' project.id %}">New card</a>{% endif %}</div>{% endif %}
|
||||
</div>
|
||||
<div class="d-flex gap-3 flex-wrap mb-3">{% for label,count in priority_counts %}<span class="badge text-bg-light border">{{ label }}: {{ count }} open</span>{% endfor %}</div>
|
||||
<form class="row g-2 mb-3" method="get" role="search">
|
||||
<div class="col"><input class="form-control" name="q" value="{{ query }}" placeholder="Search cards and specifications" aria-label="Search cards" hx-get="{% url 'projects:board' project.id %}" hx-trigger="input changed delay:300ms" hx-target="#board-results" hx-include="closest form"></div>
|
||||
<div class="col"><input class="form-control" name="q" value="{{ query }}" placeholder="Search cards and specifications" aria-label="Search cards" hx-get="{% url 'projects:board' project.id %}" hx-trigger="input changed delay:300ms" hx-target="#board-results" hx-include="closest form" hx-indicator="#board-search-loading"></div>
|
||||
<div class="col-auto"><select class="form-select" name="priority" aria-label="Priority" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All priorities</option><option value="high" {% if selected_priority == 'high' %}selected{% endif %}>High</option><option value="medium" {% if selected_priority == 'medium' %}selected{% endif %}>Medium</option><option value="low" {% if selected_priority == 'low' %}selected{% endif %}>Low</option></select></div>
|
||||
<div class="col-auto"><select class="form-select" name="card_type" aria-label="Card type" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All types</option>{% for value,label in card_types %}<option value="{{ value }}" {% if value == selected_type %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></div>
|
||||
<div class="col-auto"><select class="form-select" name="column" aria-label="Column" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All columns</option>{% for choice in columns %}<option value="{{ choice.id }}" {% if choice.id|stringformat:'s' == selected_column %}selected{% endif %}>{{ choice.name }}</option>{% endfor %}</select></div>
|
||||
@@ -15,6 +16,7 @@
|
||||
<div class="col-auto"><label><input type="checkbox" name="archived" value="1" {% if show_archived %}checked{% endif %}> Archived</label></div>
|
||||
<div class="col-auto"><a class="btn btn-outline-secondary" href="{% url 'projects:board' project.id %}">Clear</a></div>
|
||||
</form>
|
||||
<span id="board-search-loading" class="htmx-indicator" role="status">Searching…</span>
|
||||
<div id="board-results">{% include 'projects/_board.html' %}</div>
|
||||
{% if can_edit %}<a class="btn btn-outline-secondary mt-3" href="{% url 'projects:column_create' project.id %}">Add column</a>
|
||||
<a class="btn btn-outline-secondary mt-3" href="{% url 'projects:tag_create' project.id %}">Add tag</a>{% endif %}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{% extends 'core/base.html' %}{% block content %}<style>.htmx-indicator{display:none}.htmx-request.htmx-indicator,.htmx-request .htmx-indicator{display:inline}</style><div class="d-flex justify-content-between align-items-center mb-4"><div><h1>Projects</h1><p>Boards and specifications across your workspace.</p></div><a class="btn btn-success" href="{% url 'projects:create' %}">New project</a></div><p><a href="{% url 'projects:list' %}">Active</a> · <a href="{% url 'projects:list' %}?archived=1">Archived</a></p><form method="get" role="search" class="mb-3"><label for="project-search" class="form-label">Search projects and cards</label><input id="project-search" class="form-control" name="q" value="{{ query }}" hx-get="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}" hx-trigger="input changed delay:300ms" hx-target="#project-results" hx-indicator="#search-loading"><span id="search-loading" class="htmx-indicator">Searching…</span></form><div id="project-results">{% include 'projects/_project_list.html' %}</div><script src="https://unpkg.com/htmx.org@2.0.4"></script>{% endblock %}
|
||||
{% extends 'core/base.html' %}{% block content %}<style>.htmx-indicator{display:none}.htmx-request.htmx-indicator,.htmx-request .htmx-indicator{display:inline}</style><div class="d-flex justify-content-between align-items-center mb-4"><div><h1>Projects</h1><p>Boards and specifications across your workspace.</p></div><a class="btn btn-success" href="{% url 'projects:create' %}">New project</a></div><p><a href="{% url 'projects:list' %}">Active</a> · <a href="{% url 'projects:list' %}?archived=1">Archived</a></p><form method="get" role="search" class="mb-3"><label for="project-search" class="form-label">Search projects and cards</label><input id="project-search" class="form-control" name="q" value="{{ query }}" hx-get="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}" hx-trigger="input changed delay:300ms" hx-target="#project-results" hx-indicator="#search-loading"><span id="search-loading" class="htmx-indicator" role="status">Searching…</span> <a class="btn btn-sm btn-outline-secondary" href="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}">Clear</a></form><div id="project-results">{% include 'projects/_project_list.html' %}</div><script src="https://unpkg.com/htmx.org@2.0.4"></script>{% endblock %}
|
||||
|
||||
@@ -1 +1 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · Common Ground</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"></head><body class="bg-light"><main class="container" style="max-width:28rem;margin-top:12vh"><h1>Common Ground</h1><p>Sign in to your dashboard.</p><form method="post" class="card card-body">{% csrf_token %}{{ form.as_p }}<input type="hidden" name="next" value="{{ next }}"><button class="btn btn-success">Sign in</button></form>{% if oidc_enabled %}<a class="btn btn-outline-primary mt-3" href="{% url 'oidc_authentication_init' %}">Sign in with your organization</a>{% endif %}</main></body></html>
|
||||
{% load static %}<!doctype html><html lang="en" data-theme="system"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · Common Ground</title><script>document.documentElement.dataset.theme=localStorage.getItem('dashboard-theme')||'system';</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"><link rel="stylesheet" href="{% static 'core/site.css' %}"><link rel="stylesheet" href="{% static 'core/theme-bridge.css' %}"></head><body><main class="container" style="max-width:28rem;margin-top:12vh"><h1>Common Ground</h1><p>Sign in to your dashboard.</p><form method="post" class="card card-body">{% csrf_token %}{{ form.as_p }}<input type="hidden" name="next" value="{{ next }}"><button class="btn btn-success">Sign in</button></form>{% if oidc_enabled %}<a class="btn btn-outline-primary mt-3" href="{% url 'oidc_authentication_init' %}">Sign in with your organization</a>{% endif %}</main></body></html>
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
<h2 class="h5 mt-4">Connected sign-in identities</h2>
|
||||
{% for identity in identities %}<p>{{ identity.issuer }} · {{ identity.subject }}</p>{% empty %}<p>No external sign-in identity connected.</p>{% endfor %}
|
||||
<h2 class="h5 mt-4">MCP connections</h2>
|
||||
<p>Endpoint: <code>{{ mcp_url }}</code>. Authorize a registered client with <code>projects:read</code> and optionally <code>projects:write</code>. Client registration requires a signed-in account and a CSRF token for browser requests.</p>
|
||||
<p>Endpoint: <a href="{{ mcp_url }}"><code>{{ mcp_url }}</code></a>. Authorize a registered client with <code>projects:read</code> and optionally <code>projects:write</code>. Client registration requires a signed-in account and a CSRF token for browser requests.</p>
|
||||
{% if not mcp_configured %}<p class="alert alert-warning" role="status">This address differs from the configured OAuth resource URL. Set <code>MCP_PUBLIC_URL</code> to this HTTPS endpoint for both services before connecting a client.</p>{% endif %}
|
||||
{% for grant in grants %}
|
||||
<div class="card card-body mb-2" style="max-width:40rem"><strong>{{ grant.application.name|default:'Connected client' }}</strong><span>Permissions: {{ grant.scope }}</span><small>Expires {{ grant.expires }}</small><form method="post" action="{% url 'projects:revoke_connection' grant.id %}">{% csrf_token %}<button class="btn btn-sm btn-outline-danger mt-2">Revoke</button></form></div>
|
||||
{% empty %}<p>No active MCP clients.</p>{% endfor %}
|
||||
|
||||
@@ -52,7 +52,9 @@ class OAuthMcpTests(TestCase):
|
||||
self.assertIsNone(_verified(secret))
|
||||
|
||||
def test_discovery_and_project_access(self):
|
||||
self.assertEqual(self.client.get('/.well-known/oauth-authorization-server').status_code, 200)
|
||||
discovery = self.client.get('/.well-known/oauth-authorization-server')
|
||||
self.assertEqual(discovery.status_code, 200)
|
||||
self.assertIn('none', discovery.json()['token_endpoint_auth_methods_supported'])
|
||||
project = create_project(self.user, name='Private')
|
||||
self.assertEqual(self.client.get(f'/projects/{project.pk}/').status_code, 302)
|
||||
|
||||
|
||||
+42
-2
@@ -1,8 +1,12 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, override_settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.urls import reverse
|
||||
from .models import Card, CardRevision, Membership
|
||||
from django.http import HttpResponse
|
||||
from django.utils import timezone
|
||||
from .models import Card, CardRevision, Membership, Profile
|
||||
from .forms import ProfileForm
|
||||
from .middleware import ProfileTimezoneMiddleware
|
||||
from .services import RevisionConflict, card_for, create_card, create_project, move_card, update_card, update_column
|
||||
|
||||
|
||||
@@ -80,6 +84,42 @@ class ProjectWorkflowTests(TestCase):
|
||||
self.client.force_login(self.owner)
|
||||
self.assertEqual(self.client.get('/').status_code, 200)
|
||||
|
||||
def test_profile_timezone_applies_to_requests(self):
|
||||
Profile.objects.create(user=self.owner, timezone='America/New_York')
|
||||
observed = []
|
||||
|
||||
def capture(request):
|
||||
observed.append(timezone.get_current_timezone_name())
|
||||
return HttpResponse('ok')
|
||||
|
||||
request = type('Request', (), {'user': self.owner})()
|
||||
response = ProfileTimezoneMiddleware(capture)(request)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(observed, ['America/New_York'])
|
||||
self.assertEqual(timezone.get_current_timezone_name(), 'Europe/Amsterdam')
|
||||
self.assertFalse(ProfileForm(data={'timezone': 'Not/A_Timezone'}).is_valid())
|
||||
|
||||
def test_profile_mcp_url_uses_validated_https_origin(self):
|
||||
self.client.force_login(self.owner)
|
||||
public = 'https://projects.jorendegraaf.eu/mcp'
|
||||
headers = {'HTTP_HOST': 'projects.jorendegraaf.eu', 'HTTP_X_FORWARDED_PROTO': 'https'}
|
||||
with override_settings(MCP_PUBLIC_URL='https://other.example/mcp'):
|
||||
response = self.client.get(reverse('projects:profile'), **headers)
|
||||
self.assertEqual(response.context['mcp_url'], public)
|
||||
self.assertContains(response, 'This address differs from the configured OAuth resource URL.')
|
||||
with override_settings(MCP_PUBLIC_URL=public, OAUTH_ISSUER_URL='https://projects.jorendegraaf.eu/'):
|
||||
response = self.client.get(reverse('projects:profile'), **headers)
|
||||
self.assertEqual(response.context['mcp_url'], public)
|
||||
self.assertNotContains(response, 'This address differs from the configured OAuth resource URL.')
|
||||
metadata = self.client.get('/.well-known/oauth-authorization-server', **headers).json()
|
||||
self.assertEqual(metadata['issuer'], 'https://projects.jorendegraaf.eu/')
|
||||
|
||||
with override_settings(MCP_PUBLIC_URL='http://127.0.0.1:8766/mcp'):
|
||||
local = self.client.get(reverse('projects:profile'), HTTP_HOST='127.0.0.1:8765')
|
||||
self.assertEqual(local.context['mcp_url'], 'http://127.0.0.1:8766/mcp')
|
||||
rejected = self.client.get(reverse('projects:profile'), HTTP_HOST='untrusted.example')
|
||||
self.assertEqual(rejected.status_code, 400)
|
||||
|
||||
def test_login_throttles_failed_attempts(self):
|
||||
for _ in range(5):
|
||||
self.assertEqual(self.client.post('/accounts/login/', {'username': 'owner', 'password': 'wrong'}).status_code, 200)
|
||||
|
||||
+6
-1
@@ -4,6 +4,7 @@ from django.contrib.auth.views import LoginView
|
||||
from django.core.cache import cache
|
||||
from django.http import HttpResponse
|
||||
import hashlib
|
||||
from urllib.parse import urlsplit
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models import Q, Count
|
||||
from django.core.paginator import Paginator
|
||||
@@ -300,7 +301,11 @@ def profile(request):
|
||||
request.user.save(update_fields=['email'])
|
||||
return redirect('projects:profile')
|
||||
grants = get_access_token_model().objects.filter(user=request.user, expires__gt=timezone.now()).select_related('application').order_by('-created')
|
||||
return render(request, 'projects/profile.html', {'form': form, 'grants': grants, 'identities': request.user.oauth_identities.all(), 'mcp_url': settings.MCP_PUBLIC_URL, 'oidc_enabled': settings.OIDC_ENABLED, 'title': 'Profile', 'section': 'profile'})
|
||||
visiting_url = request.build_absolute_uri('/mcp')
|
||||
# Local development uses a separate MCP port; public deployments route /mcp through HTTPS.
|
||||
mcp_url = settings.MCP_PUBLIC_URL if urlsplit(visiting_url).hostname in {'localhost', '127.0.0.1', '::1'} else visiting_url
|
||||
mcp_configured = mcp_url.rstrip('/') == settings.MCP_PUBLIC_URL.rstrip('/')
|
||||
return render(request, 'projects/profile.html', {'form': form, 'grants': grants, 'identities': request.user.oauth_identities.all(), 'mcp_url': mcp_url, 'mcp_configured': mcp_configured, 'oidc_enabled': settings.OIDC_ENABLED, 'title': 'Profile', 'section': 'profile'})
|
||||
|
||||
|
||||
@login_required
|
||||
|
||||
Reference in New Issue
Block a user