7 Commits
Author SHA1 Message Date
arnef b543b46ad2 fix(web): prefill birthday in contact form for imported contacts
Docker Image bauen und veröffentlichen / docker (push) Successful in 20m27s
2026-09-06 19:27:28 +02:00
arnef 8e946964ec fix(caldav): expand RRULE for recurring events 2026-09-06 15:49:09 +02:00
arnef f35121b3dc ci: drop release trigger from docker workflow 2026-09-03 19:09:38 +02:00
arnef 83483f5cb2 docs: add AGPL-3.0 license
Docker Image bauen und veröffentlichen / docker (release) Successful in 20m49s
Docker Image bauen und veröffentlichen / docker (push) Successful in 20m57s
2026-09-03 06:20:07 +02:00
arnef 5e3cc3513c chore(ci): migrate to Gitea Actions 2026-09-02 21:53:14 +02:00
arnef f34041d889 feat(web): show ICS subscription events in detail view 2026-09-02 20:02:48 +02:00
arnef e18c83b618 feat(web): add calendar event detail view 2026-09-01 19:10:17 +02:00
24 changed files with 3442 additions and 737 deletions
@@ -3,8 +3,6 @@ name: Docker Image bauen und veröffentlichen
on: on:
push: push:
tags: ["v*"] tags: ["v*"]
release:
types: [published]
workflow_dispatch: {} workflow_dispatch: {}
env: env:
-213
View File
@@ -1,213 +0,0 @@
# Copilot Instructions for nidus
A self-hosted CalDAV, CardDAV, and WebDAV server written in Go, backed by a
filesystem store, with calendar/address book sharing grants tracked in a
small SQLite database. HTTP Basic Auth (bcrypt) with per-user isolated
collections. A small server-rendered web UI (templ + Tailwind + htmx) at
`/web/` lets users log in and manage their shares.
## Build, test, lint
```bash
make build # go build -o bin/davserver ./cmd/server
make run # build + ./bin/davserver -config config.yaml
make test # go test ./... -v -race
make lint # golangci-lint run ./...
make tidy # go mod tidy
go test ./internal/store/ -run TestStoreRoundTrip -v # single test
make templ-generate # regenerate *_templ.go after editing internal/web/templates/*.templ
make web-css # templ-generate + rebuild web/static/app.css (needs `make web-deps` once, Node.js/npm)
make web-ts # compile web/ts/*.ts to web/static/*.js
make web-assets # web-css + web-ts (everything under web/static/)
```
Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
`internal/db/shares_test.go`, `internal/caldav/backend_test.go`,
`internal/carddav/backend_test.go`, `internal/web/server_test.go`,
`tools/nidusctl/main_test.go`.
## Architecture
- `cmd/server/main.go` — entrypoint. Loads config, builds the `slog.Logger`,
constructs the `store.Store` and `db.DB`, lists all users/calendars/
address-books from the DB (`dbase.ListUsers`/`ListCalendars`/
`ListAddressBooks`) to pre-create their collections on disk, warns if
zero users exist (`nidusctl user create ...`), wires up `auth.Middleware`,
and builds the `http.ServeMux` (`buildMux`). Routes: `/cal/`, `/card/`,
`/files/`, `/.well-known/{caldav,carddav}`, `/healthz` (unauthenticated),
and `/` (welcome page on GET/HEAD only; any other method — e.g. a WebDAV
client pointed at the wrong URL — gets `405` instead of a misleading
`200`).
- `internal/config` — YAML config loading (`config.Load`), defaults
(`applyDefaults`), and validation (`validate`). Holds only server/auth/
storage/logging/TLS settings — **no user, calendar, or address-book
data**; all of that lives in `internal/db` now (see below).
- `internal/auth` — HTTP Basic Auth middleware (`auth.Middleware.Wrap`).
Takes a `*db.DB` and validates credentials via `dbase.GetUser` +
`dbase.VerifyPassword` (bcrypt), then stores a
`*Principal{Username, DisplayName, Email}` in the request context.
Downstream code retrieves it with `auth.FromContext(ctx)` — every backend
method needs this and returns `webdav.NewHTTPError(http.StatusUnauthorized, ...)`
if it's nil. `auth.NewContext(ctx, p)` is the test-only inverse, used to
build authenticated contexts without a real Basic Auth handshake.
- `internal/store` — the single source of truth for all persisted data.
A thin filesystem KV abstraction: `<data_dir>/<user>/<collection>/<objectID>`.
All collection/object names pass through `sanitize()` (via
`filepath.Base` + strip `..`) to prevent path traversal — preserve this
when adding new store methods. Writes use temp-file + rename for atomicity
(`PutObject`). Locking is sharded per-user (`lockFor(user)`, a
`map[string]*sync.RWMutex` guarded by its own mutex) rather than one
global lock, so different users' requests don't serialize against each
other.
- `internal/caldav` and `internal/carddav` — implement the
`caldav.Backend`/`carddav.Backend` interfaces from `github.com/emersion/go-webdav`
on top of `store.Store`. Calendars are stored as collections prefixed
`cal-<name>` and address books as `card-<name>` (see `ListCalendars`,
`parseCalPath`). **The URL scheme has no username segment**, but DOES
have a fixed literal `home` segment: `/cal/` (principal), `/cal/home/`
(calendar-home-set), `/cal/home/<calname>/` (calendar),
`/cal/home/<calname>/<objid>` (object) — and equivalently
`/card/`, `/card/home/`, `/card/home/<bookname>/`,
`/card/home/<bookname>/<objid>` for carddav. These are identical for
every user; the acting user always comes from `auth.FromContext(ctx)`,
never from the path. **The `home` segment is load-bearing, not
cosmetic**: go-webdav's `caldav`/`carddav` server (in the
`github.com/emersion/go-webdav` dependency, not our code) classifies
each request purely by counting URL path segments relative to the
handler's `Prefix` (which we leave `""`) — 1 segment = user principal, 2
= home-set, 3 = calendar/address book, 4 = object. If the segment counts
don't line up (e.g. removing `home` would make `/cal/` and
`/cal/<calname>/` collapse to 1 and 2 segments, misclassifying the
calendar collection itself as the home-set), PROPFIND requests silently
return an empty `<multistatus>` (200/207, zero `<response>` elements) —
no error, just nothing found, which breaks client auto-discovery (e.g.
DAVx5 reporting "no resources found"). Keep this in mind when touching
`parseCalPath`/`parseObjPath`/`parseBookPath`,
`calHomePath`/`cardHomePath`, or `CurrentUserPrincipal` — always
preserve the exact segment depth at each level. Query methods
(`QueryCalendarObjects`) currently list all objects and filter in-memory
via `caldav.Filter` — fine for small collections, not optimized for
scale.
**Sharing**: both backends take an `*db.DB` (required — used for both
the base `ListCalendars`/`ListAddressBooks`/`Create*`/`Delete*`
operations and sharing). A calendar/address book shared with a user is exposed under
the synthetic local name `<owner>~<name>` (see `sharedNameSep`,
`sharedCalendarName`/`sharedBookName`) in that user's own home-set —
`resolveCalendar`/`resolveBook` split the local name back into
owner+real name and check the grant's permission (`db.PermRead`/
`db.PermWrite`) via `dbase.CalendarShareFor`/`AddressBookShareFor`
before allowing reads (any share) or writes (write share only). The
shared data is never copied — it's read/written directly under the
owner's own `store.Store` namespace, just addressed via the synthetic
name from the grantee's requests.
- `internal/db` — a small `database/sql` wrapper around
`modernc.org/sqlite` (pure Go, no CGO) at `<data_dir>/nidus.db`. Only
one open connection is used (`SetMaxOpenConns(1)`) since SQLite allows a
single writer; this is intentionally simple and not meant to scale to
heavy concurrent write load. Schema lives in `migrate()`; there's no
migration framework, just idempotent `CREATE TABLE IF NOT EXISTS`.
Foreign keys are enabled per-connection (`?_pragma=foreign_keys(1)` in
the DSN). **This is now the single source of truth for users,
calendars, and address books** (`internal/db/users.go`):
`CreateUser`/`SetPassword`/`DeleteUser`/`GetUser`/`VerifyPassword`/
`ListUsers`, and `CreateCalendar`/`DeleteCalendar`/`ListCalendars`,
`CreateAddressBook`/`DeleteAddressBook`/`ListAddressBooks`. `users` is
the parent table; `calendars`/`addressbooks` cascade-delete via FK on
`DeleteUser`; `calendar_shares`/`addressbook_shares`/`web_sessions`
reference usernames as plain strings (no FK) so `DeleteUser` explicitly
cleans those up in a transaction. `modernc.org/sqlite` has no typed
unique-constraint error, so `isUniqueConstraintErr()` string-matches the
driver's error message.
- `internal/webdav` — plain-file WebDAV via `golang.org/x/net/webdav`,
mounted at the single fixed URL `/files/` for all users (no username in
the path either). `NewHandler` caches one `*xwebdav.Handler` per
authenticated username (keyed off `auth.FromContext`), each rooted at
`<data_dir>/files/<username>/` on disk with its own persistent
`LockSystem` — the handler (and its lock table) must be created once and
reused, not per-request, or LOCK/UNLOCK state resets on every call.
- `tools/hashpwd` — standalone CLI (`go run ./tools/hashpwd <password>`) to
generate bcrypt hashes for ad-hoc testing (no longer needed for normal
user setup — see `nidusctl user create` below).
- `tools/nidusctl` — standalone admin CLI (`go run ./tools/nidusctl
-config config.yaml <user|calendar|addressbook> ...`) — the only way to
create/delete users, calendars, and address books, plus manage sharing
grants (`calendar|addressbook share|unshare|shares`). It's a thin
argv-parsing wrapper around `db.DB`'s methods (`tools/nidusctl/main.go`
routes subcommands, `tools/nidusctl/users.go` implements `user
create/delete/list/passwd` with interactive masked password prompting
via `golang.org/x/term`, falling back to a plain stdin read when not a
TTY) — no server interaction, no daemon, no RPC; it just opens the same
SQLite file the running server uses. Changes take effect immediately
without restarting the server since nothing is cached.
- `internal/web` — the web UI, mounted at `/web/` in `cmd/server/main.go`
(`mux.Handle("/web/", http.StripPrefix("/web", web.NewServer(cfg, st,
dbase, logger).Handler(webstatic.FS())))`, so `Server.Handler`'s own
routes are all unprefixed — `/login`, `/`, `/shares/...` — and only the
outer mux adds the `/web` prefix), entirely separate from `internal/auth`'s
Basic Auth: logins go through
`/web/login` (username/password checked against the DB the same way
Basic Auth does, via `dbase.VerifyPassword`) and issue an opaque random session token
stored in the `web_sessions` SQLite table (`db.CreateSession`/
`SessionUser`/`DeleteSession`, see `internal/db/sessions.go`), set as an
`HttpOnly` cookie (`sessionCookieName` in `internal/web/session.go`).
`requireLogin` is the auth-guard middleware for authenticated routes,
storing the username in the request context (`userFromContext`).
`internal/web/dashboard.go` renders the logged-in user's own
calendars/address books plus who they're shared with
(`SharesOfCalendar`/`SharesOfAddressBook`) and what's shared with them
(`CalendarsSharedWith`/`AddressBooksSharedWith`); `resourceCards(username)`
is the shared helper (also used by `internal/web/resources.go`, see
below) that builds the list of `templates.ResourceCard`s from the DB.
`internal/web/resources.go` handles POST (create) and DELETE (delete) at
`/web/resources/{calendar,addressbook}`, validating names against
`resourceNameRe` (`^[a-zA-Z0-9_-]{1,64}$`) and re-rendering the whole
`#resources` list (`templates.ResourceList`) since the *set* of cards
changes (unlike a share update, which only touches one card).
`internal/web/shares.go`
handles POST (create/update share) and DELETE (revoke) at
`/web/shares/{calendar,addressbook}`, re-rendering just the affected
resource card for htmx's `hx-swap="outerHTML"`; it always checks
`ownsResource` first so a user can only share resources actually
configured for their own account (never someone else's, even via a
forged form post). **htmx v2 quirk**: `hx-delete` requests send
`hx-vals`/form params as URL **query string** parameters, not a request
body (unlike POST/PUT/PATCH) — `handleShare` special-cases
`r.Method == http.MethodDelete` to read from `r.URL.Query()` instead of
calling `r.ParseForm()`. Templates live in `internal/web/templates/*.templ`
(compiled to `*_templ.go` via `templ generate`/`make templ-generate` —
regenerate after editing any `.templ` file, the generated files are
committed). Styling is Tailwind v4, scanned directly over the generated
`_templ.go` files (`web/input.css`'s `@source` directives) and compiled
to `web/static/app.css` via `make web-css` (needs Node/npm — see
`web/package.json`); htmx itself is vendored as a static file
(`web/static/htmx.min.js`, not npm-installed) to avoid a CDN dependency.
Client-side-only logic (currently just the login page's password-visibility
toggle) is written in TypeScript under `web/ts/*.ts`, compiled to plain
JS via `tsc` (`web/tsconfig.json`, `make web-ts`) into `web/static/*.js`
as ES modules (`<script type="module">`). All static assets (CSS, JS,
vendored htmx) are embedded into the Go binary at build time via
`web/staticassets.go` (`//go:embed static`), so the compiled server has
no runtime dependency on Node.js or the `web/` directory being present —
Node/npm are only needed when actually changing templates/styles/TS
(`make web-assets` rebuilds everything under `web/static/`).
## Conventions
- **No username in any DAV URL** (`/cal/`, `/card/`, `/files/` are the same
for every account) — the acting user is always resolved from the Basic
Auth identity (`auth.FromContext`), never parsed out of the request path.
Don't reintroduce a `<user>` path segment when adding routes/paths.
- Path parsing in the CalDAV/CardDAV backends assumes fixed URL segment
positions (e.g. `cal/home/<calname>/<objid>`) split on `/` — see
`parseCalPath`/`parseObjPath`/`parseBookPath`. The `home` segment must
stay exactly one fixed literal segment (see note above on go-webdav's
segment-count-based resource classification) — don't remove it or add/
remove segments elsewhere without re-checking all four resource-type
depths still line up. New path-based operations should follow the same
segment-index approach for consistency.
- Store errors are sentinel values (`store.ErrNotFound`, `store.ErrConflict`)
checked with `errors.Is`/direct comparison; backends translate them into
`webdav.NewHTTPError` with the appropriate HTTP status.
- Logging uses `log/slog` structured fields (e.g. `logger.Warn("...", "user", u, "error", err)`), passed down explicitly to every constructor (`NewBackend`, `NewHandler`, `NewMiddleware`) rather than a global logger.
- Config module path is `github.com/yourusername/caldav-server` (go.mod name
predates the `nidus` repo rename) — import paths still use this, not `nidus`.
+1 -1
View File
@@ -1,4 +1,4 @@
data/ data*/
config.yaml config.yaml
web/node_modules/ web/node_modules/
/bin/ /bin/
+244
View File
@@ -0,0 +1,244 @@
Copyright (C) 2025 arnef
This program is free software licensed under the terms of the
GNU Affero General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version.
-------------------------------------------------------------
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+41 -35
View File
@@ -113,15 +113,15 @@ docker compose exec nidus nidusctl addressbook create alice contacts
This project uses year.month.hotfix versioning (e.g. `2026.8.0`, `2026.8.1`) This project uses year.month.hotfix versioning (e.g. `2026.8.0`, `2026.8.1`)
rather than semantic versioning. Pushing a version tag (e.g. `2026.8.0`) or rather than semantic versioning. Pushing a version tag (e.g. `2026.8.0`) or
publishing a release triggers publishing a release triggers
[`.github/workflows/docker-release.yml`](.github/workflows/docker-release.yml), [`.gitea/workflows/docker-release.yml`](.gitea/workflows/docker-release.yml),
which builds and publishes a multi-arch (`linux/amd64` + `linux/arm64`) which builds and publishes a multi-arch (`linux/amd64` + `linux/arm64`)
image to `git.arnef.de/arnef/nidus`, tagged with the version, `<year>.<month>`, image to `git.arnef.de/arnef/nidus`, tagged with the version, `<major>.<minor>`,
`latest`, and the short commit SHA. It authenticates via the `latest`, and the short commit SHA. It authenticates via the
`REGISTRY_USERNAME`/`REGISTRY_PASSWORD` repository secrets. `REGISTRY_USERNAME`/`REGISTRY_PASSWORD` repository secrets.
A minimal standalone `docker-compose.yml` that pulls this image instead of A minimal standalone `docker-compose.yml` that pulls this image instead of
building from a checkout — just fetch `config.example.yaml`, copy it to building from a checkout — configuration is done entirely via environment
`config.yaml`, and adjust it to your needs: variables (no `config.yaml` to copy over):
```yaml ```yaml
services: services:
@@ -182,24 +182,25 @@ grantee's own home-set alongside their own calendars — no separate account
or extra client configuration needed. or extra client configuration needed.
Sharing grants are stored in a small SQLite database at Sharing grants are stored in a small SQLite database at
`<data_dir>/nidus.db` (not in `config.yaml`) and can be managed either via `<data_dir>/nidus.db` (not in any config file) and can be managed either via
the `nidusctl` CLI or the web UI's dashboard (see below): the `nidusctl` CLI or the web UI's dashboard (see below):
```bash ```bash
# Give bob write access to alice's "work" calendar # Give bob write access to alice's "work" calendar
go run ./tools/nidusctl -config config.yaml calendar share alice work bob write go run ./tools/nidusctl calendar share alice work bob write
# List everyone alice's "work" calendar is shared with # List everyone alice's "work" calendar is shared with
go run ./tools/nidusctl -config config.yaml calendar shares alice work go run ./tools/nidusctl calendar shares alice work
# Revoke access # Revoke access
go run ./tools/nidusctl -config config.yaml calendar unshare alice work bob go run ./tools/nidusctl calendar unshare alice work bob
# Address books work the same way, using "addressbook" instead of "calendar" # Address books work the same way, using "addressbook" instead of "calendar"
go run ./tools/nidusctl -config config.yaml addressbook share alice contacts bob read go run ./tools/nidusctl addressbook share alice contacts bob read
``` ```
Or via `make`: `make nidusctl ARGS="calendar share alice work bob write"`. (Both the server and `nidusctl` resolve the data directory from the
`NIDUS_DATA_DIR` environment variable.)
A calendar that `alice` shares with `bob` appears in bob's calendar A calendar that `alice` shares with `bob` appears in bob's calendar
home-set as `/cal/home/alice~work/` (i.e. `<owner>~<calendar name>`) — the home-set as `/cal/home/alice~work/` (i.e. `<owner>~<calendar name>`) — the
@@ -225,18 +226,18 @@ mobile browsers:
place via [htmx](https://htmx.org/) without a full page reload. place via [htmx](https://htmx.org/) without a full page reload.
- **Files** (`/web/files/`) — a browser for the same storage the WebDAV - **Files** (`/web/files/`) — a browser for the same storage the WebDAV
endpoint (`/files/`) serves: navigate folders, create new folders, endpoint (`/files/`) serves: navigate folders, create new folders,
upload files/folders (including via drag & drop), download, and delete upload files/folders (including via drag & drop), download, sort by name or
files or folders. Files open **inline** in the browser when the type date, and delete files or folders. Files open **inline** in the browser when
supports it (video, audio, images, PDF, …) instead of always forcing a the type supports it (video, audio, images, PDF, …) instead of always
download; a separate "Download" action is always available to force a forcing a download; a separate "Download" action is always available to
save-as. force a save-as.
- **Contacts** (`/web/contacts/`) — browse address books, create/edit/ - **Contacts** (`/web/contacts/`) — browse address books, create/edit/
delete contacts (name, organization, birthday, phone numbers, emails, delete contacts (first/last name, organization, birthday, phone numbers,
addresses, photo), and import/export vCards (`.vcf`). emails, address, photo), and import/export vCards (`.vcf`).
- **Calendar** (`/web/calendar`) — month and week views across all your - **Calendar** (`/web/calendar`) — month and week views across all your
own and shared calendars (including ICS/webcal subscriptions and the own and shared calendars (including ICS/webcal subscriptions and the
Birthdays calendar), create/edit/delete events, per-calendar colors, Birthdays calendar), with a detail view for each event; create/edit/delete
and import/export `.ics` files. events, per-calendar colors, and import/export `.ics` files.
- **Account** (`/web/account`) — update your display name/email and - **Account** (`/web/account`) — update your display name/email and
change your password. change your password.
- **Logout** (`/web/logout`). - **Logout** (`/web/logout`).
@@ -287,7 +288,8 @@ Traefik) to terminate TLS and forward requests to the server.
## Managing users ## Managing users
All user/calendar/address-book management is done with `nidusctl` or the All user/calendar/address-book management is done with `nidusctl` or the
web UI (`/web/`). Nothing is stored in `config.yaml` anymore. web UI (`/web/`). User and resource data lives in `nidus.db`, not in a
config file.
```bash ```bash
# Users # Users
@@ -314,15 +316,10 @@ nidusctl addressbook unshare <owner> <book> <user>
nidusctl addressbook shares <owner> <book> nidusctl addressbook shares <owner> <book>
``` ```
Password are prompted for interactively (masked, double-entry) when Passwords are prompted for interactively (masked, double-entry) when
`--password` is omitted. The web UI (`/web/`) also lets a logged-in user `--password` is omitted. The web UI (`/web/`) also lets a logged-in user
create/delete their own calendars, address books, and ICS/webcal subscriptions create/delete their own calendars, address books, and ICS/webcal
from the dashboard. subscriptions from the dashboard.
> **Upgrading from an older version?** The `users:` section in
> `config.yaml` is no longer read. Recreate your users with
> `nidusctl user create` (and their calendars/address books) — there is no
> automatic migration from the old config format.
--- ---
@@ -333,19 +330,22 @@ nidus/
├── cmd/server/ # main entrypoint ├── cmd/server/ # main entrypoint
├── internal/ ├── internal/
│ ├── auth/ # HTTP Basic Auth middleware (DAV endpoints) │ ├── auth/ # HTTP Basic Auth middleware (DAV endpoints)
│ ├── caldav/ # CalDAV backend │ ├── birthdays/ # compute a virtual Birthday calendar from contacts
│ ├── caldav/ # CalDAV backend (incl. ICS subscriptions & Birthdays)
│ ├── carddav/ # CardDAV backend │ ├── carddav/ # CardDAV backend
│ ├── config/ # YAML config loader │ ├── config/ # configuration loader (environment variables)
│ ├── db/ # SQLite store (users, calendars, shares, sessions) │ ├── db/ # SQLite store (users, calendars, shares, sessions)
│ ├── icalfix/ # iCalendar (RFC 5545) parsing/fixing helpers
│ ├── icssub/ # remote ICS/webcal subscription fetcher
│ ├── store/ # filesystem storage layer │ ├── store/ # filesystem storage layer
│ ├── web/ # web UI (templ, dashboard, share mgmt, sessions)
│ │ └── templates/ # templ templates (+ generated *_templ.go)
│ └── webdav/ # WebDAV file handler │ └── webdav/ # WebDAV file handler
├── internal/web/ # web UI (templ, dashboard, share mgmt, sessions) ├── tools/nidusctl/ # admin CLI (users, calendars, address books, sharing)
│ └── templates/ # templ templates (+ generated *_templ.go) ├── tools/migrate/ # data directory migration tool
├── cmd/nidusctl/ # admin CLI (users, calendars, address books, sharing) ├── tools/hashpwd/ # standalone bcrypt password generator
├── web/ # front-end assets: Tailwind input/config, static/ ├── web/ # front-end assets: Tailwind input/config, static/
│ └── static/ # compiled app.css + htmx.min.js (embedded into the binary) │ └── static/ # compiled app.css + htmx.min.js (embedded into the binary)
├── tools/migrate/ # data directory migration tool
├── config.example.yaml # sample configuration (copy to config.yaml)
├── Dockerfile ├── Dockerfile
├── docker-compose.yaml ├── docker-compose.yaml
└── Makefile └── Makefile
@@ -371,3 +371,9 @@ reviewed and tested where practical, but not every part of the codebase
has been fully reviewed yet — use accordingly, especially before relying has been fully reviewed yet — use accordingly, especially before relying
on this in security-sensitive environments. on this in security-sensitive environments.
---
## License
nidus is licensed under the **GNU Affero General Public License v3.0 or
later (AGPL-3.0-or-later)**. See [`LICENSE`](LICENSE) for the full text.
+9 -2
View File
@@ -17,6 +17,7 @@ import (
"git.arnef.de/arnef/nidus/internal/carddav" "git.arnef.de/arnef/nidus/internal/carddav"
"git.arnef.de/arnef/nidus/internal/config" "git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db" "git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store" "git.arnef.de/arnef/nidus/internal/store"
"git.arnef.de/arnef/nidus/internal/web" "git.arnef.de/arnef/nidus/internal/web"
filewebdav "git.arnef.de/arnef/nidus/internal/webdav" filewebdav "git.arnef.de/arnef/nidus/internal/webdav"
@@ -103,10 +104,16 @@ func main() {
authMw := auth.NewMiddleware(cfg, dbase, logger) authMw := auth.NewMiddleware(cfg, dbase, logger)
// ---- Handlers ---- // ---- Handlers ----
calHandler := caldav.NewHandler(cfg, st, dbase, logger) // A single ICS-subscription cache is shared by both the CalDAV backend
// (for DAV clients) and the web UI (for the browser calendar page), so
// the same subscription is fetched and served identically regardless
// of which surface a client hits, and one background refresh refreshes
// both at once.
icsCache := icssub.NewCache(icssub.DefaultTTL)
calHandler := caldav.NewHandler(cfg, st, dbase, logger, icsCache)
cardHandler := carddav.NewHandler(cfg, st, dbase, logger) cardHandler := carddav.NewHandler(cfg, st, dbase, logger)
fileHandler := filewebdav.NewHandler(cfg, cfg.Storage.DataDir, logger) fileHandler := filewebdav.NewHandler(cfg, cfg.Storage.DataDir, logger)
webUI := web.NewServer(cfg, st, dbase, logger) webUI := web.NewServer(cfg, st, dbase, logger, icsCache)
mux := buildMux(cfg, authMw, calHandler, cardHandler, fileHandler, webUI, logger) mux := buildMux(cfg, authMw, calHandler, cardHandler, fileHandler, webUI, logger)
+117 -7
View File
@@ -41,10 +41,16 @@ type Backend struct {
icsCache *icssub.Cache icsCache *icssub.Cache
} }
// NewBackend creates a CalDAV backend. dbase may be nil, in which case // NewBackend creates a CalDAV backend over an existing ICS cache.
// calendar sharing is disabled (only a user's own calendars are visible). // dbase may be nil, in which case calendar sharing is disabled (only a
func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) *Backend { // user's own calendars are visible). The icsCache is shared with any
return &Backend{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icssub.NewCache(icssub.DefaultTTL)} // other consumers (notably the web UI) so CalDAV and the web calendar
// page see identical, cache-consistent events for ICS subscriptions.
func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger, icsCache *icssub.Cache) *Backend {
if icsCache == nil {
icsCache = icssub.NewCache(icssub.DefaultTTL)
}
return &Backend{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icsCache}
} }
// NewHandler returns an http.Handler for the /cal/ prefix. // NewHandler returns an http.Handler for the /cal/ prefix.
@@ -54,8 +60,8 @@ func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.
// property into PROPFIND responses for calendar collections, since // property into PROPFIND responses for calendar collections, since
// go-webdav's caldav.Backend interface has no extension point for // go-webdav's caldav.Backend interface has no extension point for
// vendor-specific WebDAV properties. // vendor-specific WebDAV properties.
func NewHandler(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) http.Handler { func NewHandler(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger, icsCache *icssub.Cache) http.Handler {
b := NewBackend(cfg, st, dbase, logger) b := NewBackend(cfg, st, dbase, logger, icsCache)
return &colorInjectingHandler{backend: b, next: &caldav.Handler{Backend: b}} return &colorInjectingHandler{backend: b, next: &caldav.Handler{Backend: b}}
} }
@@ -234,7 +240,16 @@ func (b *Backend) ListCalendarObjects(ctx context.Context, calPath string, req *
} }
func (b *Backend) QueryCalendarObjects(ctx context.Context, calPath string, query *caldav.CalendarQuery) ([]caldav.CalendarObject, error) { func (b *Backend) QueryCalendarObjects(ctx context.Context, calPath string, query *caldav.CalendarQuery) ([]caldav.CalendarObject, error) {
// List all and filter sufficient for small collections. if query == nil {
return b.ListCalendarObjects(ctx, calPath, nil)
}
// hoistPropFilterTimeRanges and closeOpenEndedTimeRanges are both
// idempotent and only mutate a local shallow copy of the query's
// comp-tree — the caller's original CalendarQuery is not visible
// (query is a *CalendarQuery but we only walk the value-comp fields).
hoistPropFilterTimeRanges(&query.CompFilter)
closeOpenEndedTimeRanges(&query.CompFilter)
all, err := b.ListCalendarObjects(ctx, calPath, &query.CompRequest) all, err := b.ListCalendarObjects(ctx, calPath, &query.CompRequest)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -242,6 +257,101 @@ func (b *Backend) QueryCalendarObjects(ctx context.Context, calPath string, quer
return caldav.Filter(query, all) return caldav.Filter(query, all)
} }
// hoistPropFilterTimeRanges rewrites a CompFilter in place, moving any
// prop-filter time-ranges (typically <prop-filter name="DTSTART">
// <time-range/></prop-filter>) up to the enclosing comp-filter and clearing
// them from the prop-filter. This is what fixes go-webdav's
// non-recurrence-aware matchPropTimeRange (which only compares literal
// DTSTART — so a weekly series whose base DTSTART is in 2025 gets dropped
// for a 2026 query even though its RRULE has 2026 occurrences).
//
// Lifting the range onto the enclosing comp-filter is the RFC 4791
// 9.9-equivalent for recurring components: the comp-filter's time-range is
// evaluated by go-webdav's matchCompTimeRange, which *does* expand RRULE
// (comp.RecurrenceSet) and returns true if any occurrence falls in the
// window. Non-recurring events are unaffected because the comp-level
// time-range and the prop-level time-range both check against the same
// DTSTART/DTEND.
//
// A small heuristic governs the merge:
//
// - parent has no range yet → parent.Start/End := child's range
// - parent already has a range → parent's range wins (rare / ambiguous
// client request), but the child's time-range is still cleared so
// go-webdav's literal DTSTART check doesn't re-exclude recurring
// series
//
// This runs for every comp-filter in the tree, regardless of depth, so
// both VCALENDAR>VEVENT and any other nesting the client sends are
// handled.
func hoistPropFilterTimeRanges(cf *caldav.CompFilter) {
if cf == nil {
return
}
for i := range cf.Props {
pf := &cf.Props[i]
if pf.Start.IsZero() && pf.End.IsZero() {
continue
}
if cf.Start.IsZero() {
cf.Start = pf.Start
}
if cf.End.IsZero() {
cf.End = pf.End
}
// Clear the prop-filter's own time-range so go-webdav's literal
// DTSTART check (matchPropTimeRange) doesn't re-exclude a series
// whose base DTSTART is outside the window but whose RRULE has
// occurrences in it.
pf.Start = time.Time{}
pf.End = time.Time{}
}
for i := range cf.Comps {
hoistPropFilterTimeRanges(&cf.Comps[i])
}
}
// farFutureSentinel stands in for "no upper bound" in an open-ended
// <C:time-range start="..."/> (RFC 4791 §9.9 explicitly allows a
// time-range with only a start attribute, meaning "everything from start
// onward"). It's a fixed calendar date rather than e.g. time.Now() plus
// some duration so behavior doesn't depend on when a request happens to
// run; 2100 is comfortably beyond any realistic calendar subscription's
// horizon while still bounding recurrence expansion to a finite,
// fast-to-compute range.
var farFutureSentinel = time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC)
// closeOpenEndedTimeRanges rewrites a CompFilter in place, replacing a
// zero-value End on any comp-filter that has a non-zero Start with
// farFutureSentinel.
//
// This works around a real bug (as of go-webdav v0.6.0): a client asking
// for "everything from date X onward" sends a time-range with only a
// start attribute, which decodes with End left as the zero time.Time.
// For a *non*-recurring event, go-webdav's matchCompTimeRange correctly
// treats a zero End as "unbounded" (it explicitly checks end.IsZero()).
// But for a *recurring* event, it instead calls
// rrule.Set.Between(start, end, true) unconditionally — and passing the
// zero time.Time (year 1) as the upper bound there means "before start",
// so Between always returns zero occurrences, silently excluding every
// recurring series from an open-ended query. This is exactly the shape
// of query many real CalDAV clients send for their default "sync events
// from N days in the past, no future limit" setting (e.g. DAVx5) — so
// without this workaround, a recurring series survives a bounded
// time-range query (both start and end given) but vanishes the moment a
// client asks for an unbounded future window, which is a common default.
func closeOpenEndedTimeRanges(cf *caldav.CompFilter) {
if cf == nil {
return
}
if !cf.Start.IsZero() && cf.End.IsZero() {
cf.End = farFutureSentinel
}
for i := range cf.Comps {
closeOpenEndedTimeRanges(&cf.Comps[i])
}
}
func (b *Backend) CreateCalendar(ctx context.Context, calendar *caldav.Calendar) error { func (b *Backend) CreateCalendar(ctx context.Context, calendar *caldav.Calendar) error {
p := auth.FromContext(ctx) p := auth.FromContext(ctx)
if p == nil { if p == nil {
+300 -3
View File
@@ -10,12 +10,15 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time"
"git.arnef.de/arnef/nidus/internal/auth" "git.arnef.de/arnef/nidus/internal/auth"
"git.arnef.de/arnef/nidus/internal/config" "git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db" "git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store" "git.arnef.de/arnef/nidus/internal/store"
ical "github.com/emersion/go-ical" ical "github.com/emersion/go-ical"
"github.com/emersion/go-webdav/caldav"
) )
func newTestBackend(t *testing.T) (*Backend, *db.DB) { func newTestBackend(t *testing.T) (*Backend, *db.DB) {
@@ -46,7 +49,7 @@ func newTestBackend(t *testing.T) (*Backend, *db.DB) {
t.Fatalf("CreateCalendar bob/personal: %v", err) t.Fatalf("CreateCalendar bob/personal: %v", err)
} }
logger := slog.New(slog.NewTextHandler(io.Discard, nil)) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewBackend(cfg, st, dbase, logger), dbase return NewBackend(cfg, st, dbase, logger, nil), dbase
} }
func ctxFor(username string) context.Context { func ctxFor(username string) context.Context {
@@ -179,7 +182,7 @@ func TestPropFindEmitsCalendarColor(t *testing.T) {
} }
logger := slog.New(slog.NewTextHandler(io.Discard, nil)) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
handler := NewHandler(&config.Config{}, st, dbase, logger) handler := NewHandler(&config.Config{}, st, dbase, logger, nil)
req := httptest.NewRequest("PROPFIND", "/cal/home/", strings.NewReader( req := httptest.NewRequest("PROPFIND", "/cal/home/", strings.NewReader(
`<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:allprop/></a:propfind>`)) `<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:allprop/></a:propfind>`))
@@ -250,7 +253,7 @@ func TestPropFindExplicitCalendarColorRequest(t *testing.T) {
} }
logger := slog.New(slog.NewTextHandler(io.Discard, nil)) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
handler := NewHandler(&config.Config{}, st, dbase, logger) handler := NewHandler(&config.Config{}, st, dbase, logger, nil)
req := httptest.NewRequest("PROPFIND", "/cal/home/work/", strings.NewReader( req := httptest.NewRequest("PROPFIND", "/cal/home/work/", strings.NewReader(
`<?xml version="1.0"?><D:propfind xmlns:D="DAV:" xmlns:A="http://apple.com/ns/ical/">`+ `<?xml version="1.0"?><D:propfind xmlns:D="DAV:" xmlns:A="http://apple.com/ns/ical/">`+
@@ -331,3 +334,297 @@ func TestSharedCalendarNameCollidingWithOwnGetsDisambiguated(t *testing.T) {
t.Fatalf("GetCalendar: expected display name %q, got %q", want, cal.Name) t.Fatalf("GetCalendar: expected display name %q, got %q", want, cal.Name)
} }
} }
// TestHoistPropFilterTimeRangesUnit pins the shape of the hoist rewrite:
// a prop-filter time-range (DTSTART window) is lifted onto its enclosing
// VEVENT comp-filter, and the prop-filter's own Start/End are cleared,
// so go-webdav's recurrence-aware comp-level check runs instead of its
// literal-DTSTART prop check.
func TestHoistPropFilterTimeRangesUnit(t *testing.T) {
loc := time.UTC
gs := time.Date(2026, 9, 1, 0, 0, 0, 0, loc)
ge := time.Date(2026, 9, 30, 0, 0, 0, 0, loc)
cf := caldav.CompFilter{
Name: "VCALENDAR",
Comps: []caldav.CompFilter{{
Name: "VEVENT",
Props: []caldav.PropFilter{{Name: "DTSTART", Start: gs, End: ge}},
}},
}
hoistPropFilterTimeRanges(&cf)
vevent := cf.Comps[0]
if vevent.Start != gs || vevent.End != ge {
t.Fatalf("VEVENT comp should inherit the time-range, got Start=%v End=%v", vevent.Start, vevent.End)
}
if !vevent.Props[0].Start.IsZero() || !vevent.Props[0].End.IsZero() {
t.Fatalf("prop-filter time-range must be cleared, got Start=%v End=%v", vevent.Props[0].Start, vevent.Props[0].End)
}
// The VEVENT name is untouched — hoist must not clobber component names.
if vevent.Name != "VEVENT" {
t.Fatalf("VEVENT comp name must be preserved, got %q", vevent.Name)
}
}
// rruleSample is a weekly series whose base DTSTART sits in the past
// (2025) relative to the queried 2026 window — the classic shape that
// go-webdav's literal-DTSTART prop-time-range check drops, but that a
// proper RRULE expansion keeps.
const rruleSample = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:weekly@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20250911T100000Z\r\n" + // 2025 base, far before the 2026-09 window
"DTEND:20250911T103000Z\r\n" +
"RRULE:FREQ=WEEKLY;UNTIL=20270826T080000Z;INTERVAL=3;BYDAY=TH;WKST=SU\r\n" +
"SUMMARY:Frontend Weekly\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
// TestQueryCalendarObjectsPropFilterTimeRangeRecurring is the regression
// test for the "CalDAV still misses Frontend Weekly / Abstimmung /
// Prd-Deployment" report. DAVx5 and Thunderbird issue calendar-query
// filters as <prop-filter name="DTSTART"><time-range/></prop-filter>
// *inside* a VEVENT comp-filter. go-webdav's matchPropTimeRange only
// compares the literal DTSTART (2025), so without the hoist the 2026-09
// query returns an empty result for a weekly series whose base date is
// in 2025. The hoist lifts the time-range onto the comp-filter, where
// go-webdav's recurrence-aware matchCompTimeRange (RecurrenceSet) keeps
// the series.
func TestQueryCalendarObjectsPropFilterTimeRangeRecurring(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(rruleSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("Open db: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
b := NewBackend(&config.Config{}, st, dbase, logger, icssub.NewCache(time.Hour))
ctx := auth.NewContext(context.Background(), &auth.Principal{Username: "alice"})
loc := time.UTC
gs := time.Date(2026, 9, 1, 0, 0, 0, 0, loc)
ge := time.Date(2026, 9, 30, 0, 0, 0, 0, loc)
// The DAVx5/Thunderbird form: a prop-filter time-range on DTSTART
// nested inside a VEVENT comp-filter under VCALENDAR.
q := &caldav.CalendarQuery{
CompFilter: caldav.CompFilter{
Name: "VCALENDAR",
Comps: []caldav.CompFilter{{
Name: "VEVENT",
Props: []caldav.PropFilter{{Name: "DTSTART", Start: gs, End: ge}},
}},
},
}
objs, err := b.QueryCalendarObjects(ctx, "/cal/home/holidays/", q)
if err != nil {
t.Fatalf("QueryCalendarObjects: %v", err)
}
if len(objs) == 0 {
t.Fatal("QueryCalendarObjects with a DAVx5-shape prop-filter time-range " +
"returned 0 objects for a weekly series whose RRULE has 2026-09 " +
"occurrences, but whose base DTSTART is 2025 — this is the " +
"regression the hoist fix exists to prevent")
}
found := false
for _, co := range objs {
for _, ev := range co.Data.Events() {
if p := ev.Props.Get(ical.PropSummary); p != nil && p.Value == "Frontend Weekly" {
found = true
}
}
}
if !found {
t.Fatal("expected 'Frontend Weekly' in the query result")
}
}
// TestReportPropFilterTimeRangeRecurringE2E drives the *full* HTTP stack a
// real CalDAV client uses: NewHandler → go-webdav caldav.Handler → XML decode
// of the <calendar-query>/<prop-filter>/<time-range> body →
// QueryCalendarObjects (hoist) → caldav.Filter. The in-process tests above
// hand-build the CompFilter struct and therefore skip the XML-decode step,
// so this is the only test that can catch a bug in how the client's actual
// request gets parsed. DAVx5/Thunderbird send exactly this shape.
func TestReportPropFilterTimeRangeRecurringE2E(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(rruleSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Open: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
cfg := &config.Config{}
cfg.Auth.Realm = "test"
handlers := auth.NewMiddleware(cfg, dbase, logger)
httpd := httptest.NewServer(handlers.Wrap(NewHandler(cfg, st, dbase, logger, icssub.NewCache(time.Hour))))
defer httpd.Close()
reportXML := `<?xml version="1.0" encoding="utf-8"?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:allprop/>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:prop-filter name="DTSTART">
<C:time-range start="20260901T000000Z" end="20260930T000000Z"/>
</C:prop-filter>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>`
req, err := http.NewRequest("REPORT", httpd.URL+"/cal/home/holidays/", strings.NewReader(reportXML))
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
req.SetBasicAuth("alice", "pw")
req.Header.Set("Content-Type", "application/xml; charset=utf-8")
req.Header.Set("Depth", "1")
resp, err := httpd.Client().Do(req)
if err != nil {
t.Fatalf("Do: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusMultiStatus {
t.Fatalf("REPORT status = %d, want 207; body:\n%s", resp.StatusCode, body)
}
if !strings.Contains(string(body), "Frontend Weekly") {
t.Fatalf("REPORT response did not include the recurring 'Frontend Weekly' series. This is the exact DAVx5/Thunderbird request shape; body:\n%s", body)
}
}
// TestCloseOpenEndedTimeRangesUnit exercises closeOpenEndedTimeRanges
// directly: a comp-filter with only Start set (no End) must get End
// filled in with farFutureSentinel, and a comp-filter with neither set
// must be left alone (it has no time-range at all, so there's nothing to
// "close").
func TestCloseOpenEndedTimeRangesUnit(t *testing.T) {
gs := time.Date(2026, 6, 8, 0, 0, 0, 0, time.UTC)
cf := caldav.CompFilter{
Name: "VCALENDAR",
Comps: []caldav.CompFilter{
{Name: "VEVENT", Start: gs}, // open-ended: no End
{Name: "VTODO"}, // no time-range at all
},
}
closeOpenEndedTimeRanges(&cf)
if cf.Comps[0].End != farFutureSentinel {
t.Fatalf("open-ended VEVENT comp-filter should get End=farFutureSentinel, got %v", cf.Comps[0].End)
}
if !cf.Comps[1].Start.IsZero() || !cf.Comps[1].End.IsZero() {
t.Fatalf("VTODO comp-filter without any time-range must be left untouched, got Start=%v End=%v",
cf.Comps[1].Start, cf.Comps[1].End)
}
}
// TestQueryCalendarObjectsOpenEndedTimeRangeRecurring is the regression
// test for a real bug found while investigating the "missing recurring
// events" report: a client asking for "everything from date X onward"
// (RFC 4791 §9.9 explicitly permits a time-range with only a start
// attribute) — which is exactly what a client's default "sync events
// from N days in the past, no future limit" setting produces — decodes
// with End left as the zero time.Time. go-webdav's matchCompTimeRange
// then calls rrule.Set.Between(start, zero-time, true) for any recurring
// event, which always returns zero occurrences (the "end" bound is year
// 1, before "start"), so *every* recurring series silently vanishes from
// an open-ended query, even though the exact same series matches fine
// when the client happens to also send an explicit (bounded) end date.
func TestQueryCalendarObjectsOpenEndedTimeRangeRecurring(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(rruleSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("Open db: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
b := NewBackend(&config.Config{}, st, dbase, logger, icssub.NewCache(time.Hour))
ctx := auth.NewContext(context.Background(), &auth.Principal{Username: "alice"})
// "Sync from 90 days ago, no future limit": only Start is set.
gs := time.Date(2026, 6, 8, 0, 0, 0, 0, time.UTC)
q := &caldav.CalendarQuery{
CompFilter: caldav.CompFilter{
Name: "VCALENDAR",
Comps: []caldav.CompFilter{{
Name: "VEVENT",
Start: gs, // no End: open-ended
}},
},
}
objs, err := b.QueryCalendarObjects(ctx, "/cal/home/holidays/", q)
if err != nil {
t.Fatalf("QueryCalendarObjects: %v", err)
}
found := false
for _, co := range objs {
for _, ev := range co.Data.Events() {
if p := ev.Props.Get(ical.PropSummary); p != nil && p.Value == "Frontend Weekly" {
found = true
}
}
}
if !found {
t.Fatal("expected 'Frontend Weekly' to match an open-ended (start-only) time-range query")
}
}
+28 -51
View File
@@ -1,8 +1,6 @@
package caldav package caldav
import ( import (
"crypto/sha1"
"encoding/hex"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
@@ -13,6 +11,7 @@ import (
"github.com/emersion/go-webdav/caldav" "github.com/emersion/go-webdav/caldav"
"git.arnef.de/arnef/nidus/internal/db" "git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
) )
// defaultICSColor is the display color for an ICS/webcal subscription // defaultICSColor is the display color for an ICS/webcal subscription
@@ -31,26 +30,14 @@ func (b *Backend) icsSubscriptionCalendarMeta(owner string, sub db.ICSSubscripti
} }
} }
// icsObjectUID returns the UID a fetched VEVENT should be addressed by: // icsSubscriptionCalendarObjects fetches sub's remote calendar (via
// its own UID property if it has one, otherwise a stable hash of its // b.icsCache) and returns one caldav.CalendarObject per Series — the
// position so it still round-trips consistently between requests. // source feed's own group of VEVENTs sharing a UID (a recurring base plus
func icsObjectUID(ev ical.Event, fallback string) string { // its explicit per-occurrence instances). Exposing the whole group as a
if p := ev.Props.Get(ical.PropUID); p != nil && p.Value != "" { // single object is the correct, non-lossy shape: a CalDAV client keeps the
return p.Value // entire series (RRULE + overrides) instead of the base and its instances
} // arriving as competing objects. The object path is derived from
return fallback // series.ID(), stable across fetches of the same feed.
}
// icsObjID builds the object ID (file-name-like, ".ics" suffixed) used to
// address a fetched VEVENT within its subscription calendar, derived from
// its UID so it stays stable across fetches of the same feed.
func icsObjID(uid string) string {
sum := sha1.Sum([]byte(uid))
return hex.EncodeToString(sum[:]) + ".ics"
}
// listICSSubscriptionCalendarObjects fetches sub's remote calendar (via
// b.icsCache) and returns one caldav.CalendarObject per VEVENT.
func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.ICSSubscription) ([]caldav.CalendarObject, error) { func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.ICSSubscription) ([]caldav.CalendarObject, error) {
cal, err := b.icsCache.Get(sub.URL) cal, err := b.icsCache.Get(sub.URL)
if err != nil { if err != nil {
@@ -58,8 +45,11 @@ func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.IC
} }
var objs []caldav.CalendarObject var objs []caldav.CalendarObject
for i, ev := range cal.Events() { for _, series := range icssub.GroupSeries(cal) {
obj, err := b.encodeICSObject(localName, ev, fmt.Sprintf("event-%d", i)) if series.Base == nil && len(series.Instances) == 0 {
continue
}
obj, err := b.encodeICSSeries(localName, series)
if err != nil { if err != nil {
continue continue
} }
@@ -69,50 +59,37 @@ func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.IC
} }
// icsSubscriptionCalendarObject fetches sub's remote calendar and returns // icsSubscriptionCalendarObject fetches sub's remote calendar and returns
// the single VEVENT whose derived object ID matches objID. // the Series whose stable ID matches objID.
func (b *Backend) icsSubscriptionCalendarObject(localName, objID string, sub db.ICSSubscription) (*caldav.CalendarObject, error) { func (b *Backend) icsSubscriptionCalendarObject(localName, objID string, sub db.ICSSubscription) (*caldav.CalendarObject, error) {
cal, err := b.icsCache.Get(sub.URL) cal, err := b.icsCache.Get(sub.URL)
if err != nil { if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("fetching ics subscription: %w", err)) return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("fetching ics subscription: %w", err))
} }
for i, ev := range cal.Events() { for _, series := range icssub.GroupSeries(cal) {
uid := icsObjectUID(ev, fmt.Sprintf("event-%d", i)) if series.Base == nil && len(series.Instances) == 0 {
if icsObjID(uid) != objID {
continue continue
} }
return b.encodeICSObject(localName, ev, fmt.Sprintf("event-%d", i)) if series.ID() != objID {
continue
}
return b.encodeICSSeries(localName, series)
} }
return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("ics subscription event not found")) return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("ics subscription event not found"))
} }
// encodeICSObject wraps a single fetched VEVENT ev into its own // encodeICSSeries wraps a Series (base VEVENT + explicit instances, all the
// caldav.CalendarObject, encoding it as a standalone one-event calendar // feed's events that share a UID) into its own caldav.CalendarObject,
// the same way every other calendar object in this backend is // encoded as a multi-VEVENT VCALENDAR the same way the source subscription
// represented. fallbackUID is used to derive the object ID/UID if ev has // is published.
// no UID property of its own. func (b *Backend) encodeICSSeries(localName string, series *icssub.Series) (*caldav.CalendarObject, error) {
func (b *Backend) encodeICSObject(localName string, ev ical.Event, fallbackUID string) (*caldav.CalendarObject, error) { out := series.Calendar()
uid := icsObjectUID(ev, fallbackUID)
objID := icsObjID(uid)
event := ical.NewEvent()
event.Props = ev.Props
if event.Props.Get(ical.PropUID) == nil {
event.Props.SetText(ical.PropUID, uid)
}
if event.Props.Get(ical.PropDateTimeStamp) == nil {
event.Props.SetDateTime(ical.PropDateTimeStamp, time.Now().UTC())
}
out := ical.NewCalendar()
out.Props.SetText(ical.PropVersion, "2.0")
out.Props.SetText(ical.PropProductID, "-//nidus//ics-subscription//EN")
out.Children = append(out.Children, event.Component)
var buf strings.Builder var buf strings.Builder
if err := ical.NewEncoder(&buf).Encode(out); err != nil { if err := ical.NewEncoder(&buf).Encode(out); err != nil {
return nil, fmt.Errorf("encoding ics subscription event: %w", err) return nil, fmt.Errorf("encoding ics subscription event: %w", err)
} }
data := []byte(buf.String()) data := []byte(buf.String())
objID := series.ID()
return &caldav.CalendarObject{ return &caldav.CalendarObject{
Path: calObjectPath(localName, objID), Path: calObjectPath(localName, objID),
+281
View File
@@ -0,0 +1,281 @@
package caldav
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"git.arnef.de/arnef/nidus/internal/auth"
"git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store"
ical "github.com/emersion/go-ical"
)
// icsSample is a minimal valid ICS feed with one VEVENT.
const icsSample = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:shared1@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260805T090000Z\r\n" +
"DTEND:20260805T100000Z\r\n" +
"SUMMARY:Shared event\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
// mustCalEvent parses raw and returns its first VEVENT (panic on error;
// safe in tests).
func mustCalEvent(t *testing.T, raw string) ical.Event {
t.Helper()
_ = t
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
if err != nil {
panic("mustCalEvent: " + err.Error())
}
evs := cal.Events()
if len(evs) == 0 {
panic("mustCalEvent: no events")
}
return evs[0]
}
// icssubSeriesID returns the stable ID the CalDAV backend advertises for the
// (single) series in raw. All tests here use single-series feeds, so this is
// just GroupSeries(raw)[0].ID().
func icssubSeriesID(t *testing.T, raw string) string {
t.Helper()
_ = t
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
if err != nil {
panic("icssubSeriesID: " + err.Error())
}
series := icssub.GroupSeries(cal)
if len(series) == 0 {
panic("icssubSeriesID: no series")
}
return series[0].ID()
}
// TestICSSubscriptionListAndGetObject verifies the full CalDAV read path
// for an ICS subscription: ListCalendarObjects returns one synthetic
// stand-alone object whose Path is derived from icssub.EventID (not from
// the event's position), and the same object is returned via
// GetCalendarObject by the same Path.
func TestICSSubscriptionListAndGetObject(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Open: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
b := NewBackend(&config.Config{}, st, dbase, logger, icssub.NewCache(time.Hour))
ctx := auth.NewContext(context.Background(), &auth.Principal{Username: "alice"})
objs, err := b.ListCalendarObjects(ctx, "/cal/home/holidays/", nil)
if err != nil {
t.Fatalf("ListCalendarObjects: %v", err)
}
if len(objs) != 1 {
t.Fatalf("expected 1 object, got %d", len(objs))
}
// The Path must be derived from the event's stable identity (its UID) —
// i.e. the series ID — not from the event's position in the feed.
wantID := icssubSeriesID(t, icsSample)
wantPath := calObjectPath("holidays", wantID)
if objs[0].Path != wantPath {
t.Fatalf("Path = %q, want %q (series-ID-based, not position-based)", objs[0].Path, wantPath)
}
// GetCalendarObject by the same Path should return an object that has
// a valid VEVENT whose UID matches our source ICS (round-trip
// correctness).
found, err := b.GetCalendarObject(ctx, objs[0].Path, nil)
if err != nil {
t.Fatalf("GetCalendarObject: %v", err)
}
if found.Path != objs[0].Path {
t.Fatalf("round-trip path mismatch: %q vs %q", found.Path, objs[0].Path)
}
if found.Data == nil || len(found.Data.Events()) == 0 {
t.Fatalf("expected found.Data to have >=1 event, got %+v", found.Data)
}
uid := found.Data.Events()[0].Props.Get(ical.PropUID)
if uid == nil || uid.Value != "shared1@nidus.test" {
t.Fatalf("expected UID shared1@nidus.test in round-tripped event, got %+v", uid)
}
}
// TestIcssubCacheSharedBetweenConsumersInCalDav verifies that one
// *icssub.Cache shared by two different callers of the same backend does
// not re-fetch the upstream twice (the second caller sees the cached
// copy via the singleflight guard), proving the "return cached value and
// update in the background" design is reachable from the CalDAV API.
func TestIcssubCacheSharedBetweenConsumersInCalDav(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
// Sleep long enough that *if* the second Get blocked, this
// test's wall clock would obviously exceed the bound below.
time.Sleep(30 * time.Millisecond)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Open: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
// One cache, shared by two backends on the same DB — mirrors the
// production wiring (cmd/server/main.go) where the CalDAV and web UI
// share one instance.
shared := icssub.NewCache(time.Hour)
b1 := NewBackend(&config.Config{}, st, dbase, logger, shared)
b2 := NewBackend(&config.Config{}, st, dbase, logger, shared)
ctx := auth.NewContext(context.Background(), &auth.Principal{Username: "alice"})
if _, err := b1.ListCalendarObjects(ctx, "/cal/home/holidays/", nil); err != nil {
t.Fatalf("backend 1 list: %v", err)
}
after1 := hits.Load()
if _, err := b2.ListCalendarObjects(ctx, "/cal/home/holidays/", nil); err != nil {
t.Fatalf("backend 2 list: %v", err)
}
after2 := hits.Load()
if after2 > after1+1 {
t.Fatalf("expected shared cache to coalesce (hits %d → %d)", after1, after2)
}
}
// TestIcssubCacheStaleReturnsWithBackgroundRefresh verifies the
// stale-while-revalidate path through the public Cache API: a cached
// entry past its TTL is still returned immediately (never blocking the
// caller for the slow 30 ms fetch), while a background refresh updates
// the entry for the next Get.
func TestIcssubCacheStaleReturnsWithBackgroundRefresh(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
time.Sleep(50 * time.Millisecond)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsSample))
}))
defer srv.Close()
c := icssub.NewCache(2 * time.Millisecond) // very short TTL
if _, err := c.Get(srv.URL); err != nil {
t.Fatalf("first Get: %v", err)
}
firstHits := hits.Load()
time.Sleep(5 * time.Millisecond) // force staleness
st := time.Now()
if _, err := c.Get(srv.URL); err != nil {
t.Fatalf("stale Get: %v", err)
}
if time.Since(st) > 40*time.Millisecond {
t.Fatalf("stale Get blocked on the network for %v — should have returned the cached copy", time.Since(st))
}
// Wait for the background refresh to land.
deadline := time.Now().Add(2 * time.Second)
for hits.Load() == firstHits && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if hits.Load() == firstHits {
t.Fatalf("background refresh did not fire (hits stayed at %d)", firstHits)
}
}
// TestICSSubscriptionEventIDMatchesEventInCalDav proves that the object
// path the CalDAV backend advertises (in ListCalendarObjects) is exactly
// the same string the EventDetailPage-style lookup would use on the web
// side — i.e. both surfaces agree on what icssub.EventID(ev) produces.
func TestICSSubscriptionEventIDMatchesEventInCalDav(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsSample))
}))
defer srv.Close()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
dbase, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Open: %v", err)
}
defer dbase.Close()
if err := dbase.CreateUser("alice", "pw", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := dbase.CreateICSSubscription("alice", "holidays", srv.URL, ""); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
b := NewBackend(&config.Config{}, st, dbase, logger, icssub.NewCache(time.Hour))
ctx := auth.NewContext(context.Background(), &auth.Principal{Username: "alice"})
objs, err := b.ListCalendarObjects(ctx, "/cal/home/holidays/", nil)
if err != nil || len(objs) == 0 {
t.Fatalf("list: objs=%d err=%v", len(objs), err)
}
gotPath := objs[0].Path
wantID := icssubSeriesID(t, icsSample)
wantPath := calObjectPath("holidays", wantID)
if gotPath != wantPath {
t.Fatalf("CalDAV object path %q does not match web-side EventID-derived %q", gotPath, wantPath)
}
}
+20 -3
View File
@@ -27,8 +27,20 @@ import "regexp"
var tzidParamRe = regexp.MustCompile(`TZID=("?)([^";:\r\n]+)("?)`) var tzidParamRe = regexp.MustCompile(`TZID=("?)([^";:\r\n]+)("?)`)
// tzidLineRe matches a standalone "TZID:<name>" property line, as found // tzidLineRe matches a standalone "TZID:<name>" property line, as found
// inside a VTIMEZONE component. // inside a VTIMEZONE component. The trailing "(\r?)" capture group is
var tzidLineRe = regexp.MustCompile(`(?m)^TZID:([^\r\n]+)$`) // required, not cosmetic: Go's RE2 engine only matches "$" in multi-line
// mode immediately before a literal "\n", not before "\r\n" — so without
// consuming (and re-emitting) an optional trailing "\r" explicitly, this
// regex silently fails to match on any CRLF-terminated feed (which is
// every Outlook/Exchange-published ICS feed in practice), leaving the
// VTIMEZONE's own TZID line un-normalized even though the "TZID=..."
// parameter form (tzidParamRe, used on DTSTART/DTEND/etc.) still matches
// fine. The practical effect was a VTIMEZONE whose declared TZID
// ("W. Europe Standard Time") never matched the now-normalized
// "TZID=Europe/Berlin" parameters referencing it elsewhere in the same
// object, so any code trying to find "the VTIMEZONE for Europe/Berlin"
// (see internal/icssub.Series.referencedTimezones) would never find one.
var tzidLineRe = regexp.MustCompile(`(?m)^TZID:([^\r\n]+)(\r?)$`)
// NormalizeTimeZones rewrites any recognized Windows timezone identifier // NormalizeTimeZones rewrites any recognized Windows timezone identifier
// in data to its IANA equivalent, leaving everything else (including // in data to its IANA equivalent, leaving everything else (including
@@ -51,7 +63,12 @@ func NormalizeTimeZones(data []byte) []byte {
if !ok { if !ok {
return m return m
} }
return []byte("TZID:" + iana) // sub[2] is the optional trailing "\r" the regex consumed as part
// of the match (see the doc comment above) — it must be re-emitted
// here, or a CRLF-terminated line loses its "\r" and every
// subsequent line in the file ends up misaligned relative to the
// original byte offsets a caller might have recorded.
return []byte("TZID:" + iana + string(sub[2]))
}) })
return data return data
} }
+33
View File
@@ -69,3 +69,36 @@ func TestNormalizeTimeZonesLeavesUnknownAndIANAZonesAlone(t *testing.T) {
t.Fatalf("expected data to be unchanged, got:\n%s", got) t.Fatalf("expected data to be unchanged, got:\n%s", got)
} }
} }
// TestNormalizeTimeZonesFixesVTIMEZONECRLFLine reproduces a real bug: the
// standalone "TZID:<name>" property line inside a VTIMEZONE component
// (as opposed to a "TZID=<name>" parameter on DTSTART/DTEND/etc.) was
// never being normalized on real-world feeds, because every
// Outlook/Exchange-published ICS uses CRLF line endings and Go's RE2 "$"
// anchor in multi-line mode only matches immediately before a literal
// "\n" — not before "\r\n". So on a line like
// "TZID:W. Europe Standard Time\r\n", the old
// `^TZID:([^\r\n]+)$` pattern never matched at all, leaving the
// VTIMEZONE's own declared TZID un-normalized while every "TZID=..."
// parameter elsewhere in the same object WAS normalized (that regex has
// no such issue) — so nothing referencing the VTIMEZONE by name could
// ever find it again. See internal/icssub.Series.referencedTimezones,
// which depends on exactly this match to embed the right VTIMEZONE in a
// synthetic per-series VCALENDAR.
func TestNormalizeTimeZonesFixesVTIMEZONECRLFLine(t *testing.T) {
const raw = "BEGIN:VCALENDAR\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:W. Europe Standard Time\r\n" +
"END:VTIMEZONE\r\n" +
"END:VCALENDAR\r\n"
const want = "BEGIN:VCALENDAR\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:Europe/Berlin\r\n" +
"END:VTIMEZONE\r\n" +
"END:VCALENDAR\r\n"
got := string(NormalizeTimeZones([]byte(raw)))
if got != want {
t.Fatalf("CRLF-terminated VTIMEZONE TZID line was not normalized:\ngot: %q\nwant: %q", got, want)
}
}
+394 -29
View File
@@ -7,6 +7,8 @@ package icssub
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -19,8 +21,8 @@ import (
"git.arnef.de/arnef/nidus/internal/icalfix" "git.arnef.de/arnef/nidus/internal/icalfix"
) )
// DefaultTTL is how long a fetched calendar is cached before being // DefaultTTL is how long a fetched calendar is considered "fresh" before a
// re-fetched on the next access. // Get will kick off a background refresh.
const DefaultTTL = 15 * time.Minute const DefaultTTL = 15 * time.Minute
// fetchTimeout bounds how long a single upstream request may take, so one // fetchTimeout bounds how long a single upstream request may take, so one
@@ -32,54 +34,143 @@ const fetchTimeout = 15 * time.Second
// response. // response.
const maxBodySize = 32 * 1024 * 1024 // 32 MiB const maxBodySize = 32 * 1024 * 1024 // 32 MiB
// entry holds everything the Cache knows about a single upstream URL. All
// fields are only read/written while holding Cache.mu.
type entry struct { type entry struct {
url string // original URL as supplied by the caller (fetch normalizes)
// cal is the most recent successfully-fetched calendar. Nil until the
// first successful fetch for this URL.
cal *ical.Calendar
// lastErr is the most recent fetch error. Set alongside cal == nil
// (i.e. no successful fetch yet); cleared the moment a fetch succeeds.
lastErr error
// refreshing is true while a fetch (foreground, or background refresh)
// is in flight for this URL.
refreshing bool
// pending is the completion channel for the in-flight fetch. Only valid
// while refreshing is true; it is created fresh for each fetch and
// closed exactly once when that fetch finishes. Callers that see
// refreshing==true read this channel (under the lock) and wait on it.
pending chan struct{}
// fetchedAt is the wall-clock time of the most recent fetch attempt
// (success or failure), used for the TTL freshness check.
fetchedAt time.Time fetchedAt time.Time
cal *ical.Calendar
err error
} }
// Cache fetches remote ICS calendars over HTTP(S), keeping a short-lived // Cache fetches remote ICS calendars over HTTP(S), keeping a shared
// in-memory copy per URL so repeated renders (e.g. every month-view page // in-memory copy per URL. Semantics:
// load, or CalDAV client polling) don't re-fetch the same subscription //
// from origin every time. // - Fresh entry (fetchedAt within TTL): return immediately, no I/O.
// - Stale entry with a cached copy: return the stale copy immediately
// AND spawn at most one background refresher (other callers in the
// same window piggyback on the in-flight refresh).
// - Stale entry with no cached copy (prior fetch failed): return the
// cached error immediately AND spawn a background retry.
// - No entry at all (very first call for this URL): block until a
// foreground fetch finishes (concurrent first-callers wait on a shared
// channel and all get the same result) and return its data.
type Cache struct { type Cache struct {
ttl time.Duration ttl time.Duration
client *http.Client client *http.Client
mu sync.Mutex mu sync.Mutex
entries map[string]entry urls map[string]*entry // keyed by normalizeURL(url)
} }
// NewCache creates a Cache with the given TTL (use DefaultTTL if unsure). // NewCache creates a Cache with the given TTL (use DefaultTTL if unsure).
func NewCache(ttl time.Duration) *Cache { func NewCache(ttl time.Duration) *Cache {
return &Cache{ return &Cache{
ttl: ttl, ttl: ttl,
client: &http.Client{Timeout: fetchTimeout}, client: &http.Client{},
entries: make(map[string]entry), urls: make(map[string]*entry),
} }
} }
// Get returns the parsed calendar fetched from url, using a cached copy // Get returns the most recently successfully-fetched calendar for url, or
// if it's still within the TTL. If a fresh fetch fails but a previously // the most-recent fetch error if no successful copy exists yet (a
// fetched copy exists, the stale copy is returned instead of the error, // background refresher may already be retrying).
// so a transient network issue doesn't blank out the calendar entirely.
func (c *Cache) Get(url string) (*ical.Calendar, error) { func (c *Cache) Get(url string) (*ical.Calendar, error) {
key := normalizeURL(url)
c.mu.Lock() c.mu.Lock()
e, ok := c.entries[url] e := c.urls[key]
fresh := ok && time.Since(e.fetchedAt) < c.ttl if e == nil {
c.mu.Unlock() e = &entry{url: url}
if fresh { c.urls[key] = e
return e.cal, e.err
} }
cal, err := c.fetch(url) switch {
c.mu.Lock() case e.cal == nil && e.lastErr == nil && !e.refreshing:
defer c.mu.Unlock() // Very first request for this URL: do a foreground fetch.
if err != nil && ok && e.cal != nil { e.refreshing = true
return e.cal, nil e.pending = make(chan struct{})
ch := e.pending
c.mu.Unlock()
go c.doFetch(e, ch)
<-ch
return c.snapshot(e)
case e.cal == nil && e.lastErr == nil:
// A foreground fetch is already in flight — wait for it.
ch := e.pending
c.mu.Unlock()
<-ch
return c.snapshot(e)
default:
// We have some data (a cached copy or a cached error).
if time.Since(e.fetchedAt) < c.ttl {
// Fresh — just return.
c.mu.Unlock()
return c.snapshot(e)
}
// Stale — return the cached value immediately; spawn at most one
// background refresher (or piggyback on one already in flight).
if !e.refreshing {
e.refreshing = true
ch := make(chan struct{})
e.pending = ch
c.mu.Unlock()
go c.doFetch(e, ch)
} else {
c.mu.Unlock()
}
return c.snapshot(e)
} }
c.entries[url] = entry{fetchedAt: time.Now(), cal: cal, err: err} }
return cal, err
// doFetch performs the network I/O for the entry, updates cal/lastErr and
// the freshness timestamp under the lock, clears the in-flight state, and
// closes the per-fetch completion channel exactly once.
func (c *Cache) doFetch(e *entry, ch chan struct{}) {
cal, err := c.fetch(e.url)
c.mu.Lock()
e.fetchedAt = time.Now()
if err == nil {
e.cal = cal
e.lastErr = nil
} else {
e.lastErr = err
}
e.refreshing = false
e.pending = nil
c.mu.Unlock()
close(ch)
}
// snapshot reads e.cal/e.lastErr under c.mu and returns the same value
// shape Get does. Callers must not hold c.mu.
func (c *Cache) snapshot(e *entry) (*ical.Calendar, error) {
c.mu.Lock()
cal, err := e.cal, e.lastErr
c.mu.Unlock()
if cal != nil {
return cal, nil
}
return nil, err
} }
// fetch downloads and parses url, translating a "webcal://" scheme (used // fetch downloads and parses url, translating a "webcal://" scheme (used
@@ -128,3 +219,277 @@ func normalizeURL(u string) string {
} }
return u return u
} }
// Series is one addressable calendar entity in a fetched ICS/calendar
// subscription feed: all VEVENTs that share the same UID, or — for feeds
// that omit UIDs — that hash to the same EventID, grouped together.
//
// This matches how Outlook / Exchange publish recurring events ("fully
// expanded" ICS): one <b>base</b> VEVENT carrying the RRULE, plus one bare
// <b>instance</b> VEVENT per explicit occurrence (per-instance edits,
// one-off additions, "Canceled:" overrides) — all under the SAME UID.
// Treating the base and each instance as separate events is what produces
// the two visible bugs, so everything on the subscription path
// (web grid, CalDAV objects, detail page) is keyed off the Series, not off
// individual VEVENTs:
//
// - the web month/week grid paints ONE entry per (series, day), so a day
// covered by both the RRULE base and an explicit instance is not
// rendered twice;
// - the CalDAV backend advertises ONE calendar object per series, whose
// VCALENDAR holds the base + all instances — the shape the source feed
// uses — so clients keep the whole series instead of dropping it.
//
// A series has at least one of Base or a non-empty Instances; Key is
// stable across fetches and is the only thing callers address it by.
type Series struct {
Key string
Base *ical.Event // the VEVENT carrying the RRULE, if any
Instances []ical.Event // the explicit per-occurrence VEVENTs
// tzs holds every VTIMEZONE component from the source feed (shared
// across all series parsed from the same feed). Calendar() embeds
// whichever of these are actually referenced by this series' VEVENTs,
// so the synthetic per-series VCALENDAR stays RFC 5545-compliant. See
// Calendar's doc comment for why this matters.
tzs []*ical.Component
}
// ID returns a stable filesystem-name/URL-path identifier for the series
// (32 hex chars + ".ics"), derived from the series Key. Two different
// series never collide; the same series keeps the same ID across
// refetches of the same feed.
func (s *Series) ID() string {
sum := sha256.Sum256([]byte("series:" + s.Key))
return hex.EncodeToString(sum[:16]) + ".ics"
}
// GroupSeries folds all VEVENTs of cal into Series, one per UID (falling
// back to EventID for feeds without UIDs). Within a series the VEVENT that
// carries an RRULE becomes Base; every other VEVENT is an Instance. The
// returned slice preserves the feed's first-seen order of each series.
func GroupSeries(cal *ical.Calendar) []*Series {
if cal == nil {
return nil
}
// Collect every VTIMEZONE the feed defines, so each series can embed
// whichever ones its own VEVENTs actually reference (see Calendar).
var tzs []*ical.Component
for _, child := range cal.Children {
if child.Name == ical.CompTimezone {
tzs = append(tzs, child)
}
}
byKey := make(map[string]*Series)
var order []string
for _, ev := range cal.Events() {
var key string
if uid := ev.Props.Get(ical.PropUID); uid != nil && uid.Value != "" {
key = "uid=" + uid.Value
} else if id := EventID(ev); id != "" {
key = "eid=" + id
} else {
continue // not addressable
}
s := byKey[key]
if s == nil {
s = &Series{Key: key, tzs: tzs}
byKey[key] = s
order = append(order, key)
}
if ev.Props.Get(ical.PropRecurrenceRule) != nil {
if s.Base == nil {
s.Base = &ev
}
} else {
s.Instances = append(s.Instances, ev)
}
}
out := make([]*Series, 0, len(order))
for _, key := range order {
out = append(out, byKey[key])
}
return out
}
// Anchor returns the VEVENT that best represents the series for display of
// a single occurrence: the recurring Base when present, otherwise the
// earliest Instance. It is nil for an empty series.
func (s *Series) Anchor() *ical.Event {
if s.Base != nil {
return s.Base
}
best := -1
for i := range s.Instances {
if best == -1 || dtStartEarlier(s.Instances[i], s.Instances[best]) {
best = i
}
}
if best == -1 {
return nil
}
return &s.Instances[best]
}
// Calendar returns a fresh, self-contained ical.Calendar holding every
// VEVENT of the series (base first, then instances in feed order), i.e. the
// source feed's own group of events — suitable to encode as one CalDAV
// calendar object and for the subscription detail page.
//
// It also embeds every VTIMEZONE component (copied from the source feed)
// that's actually referenced by one of the series' own VEVENTs (via a
// TZID parameter on DTSTART/DTEND/RECURRENCE-ID/EXDATE/RDATE). Per RFC
// 5545 §3.6.5, a TZID that isn't "UTC" or a bare offset MUST have a
// matching VTIMEZONE definition in the same iCalendar object. Without it,
// strict parsers (notably ical4j, which DAVx5 is built on) can fail to
// resolve the timezone for recurrence-rule expansion and silently drop
// the whole VEVENT — which is exactly what made recurring events
// (e.g. a weekly meeting) vanish from CalDAV clients even though the
// event listing/query logic itself was correct: each series used to be
// encoded as a bare VEVENT-only VCALENDAR with no VTIMEZONE at all.
func (s *Series) Calendar() *ical.Calendar {
out := ical.NewCalendar()
out.Props.SetText(ical.PropVersion, "2.0")
out.Props.SetText(ical.PropProductID, "-//nidus//ics-subscription//EN")
for _, tz := range s.referencedTimezones() {
out.Children = append(out.Children, tz)
}
if s.Base != nil {
out.Children = append(out.Children, s.Base.Component)
}
for i := range s.Instances {
out.Children = append(out.Children, s.Instances[i].Component)
}
return out
}
// referencedTimezones returns the subset of s.tzs whose TZID is
// referenced by any property of s.Base or s.Instances, preserving s.tzs'
// original order and including each matched VTIMEZONE at most once.
func (s *Series) referencedTimezones() []*ical.Component {
if len(s.tzs) == 0 {
return nil
}
needed := make(map[string]bool)
note := func(ev *ical.Event) {
if ev == nil {
return
}
for _, props := range ev.Props {
for _, p := range props {
if tzid := p.Params.Get(ical.PropTimezoneID); tzid != "" {
needed[tzid] = true
}
}
}
}
note(s.Base)
for i := range s.Instances {
note(&s.Instances[i])
}
if len(needed) == 0 {
return nil
}
var out []*ical.Component
for _, tz := range s.tzs {
tzidProp := tz.Props.Get(ical.PropTimezoneID)
if tzidProp == nil || !needed[tzidProp.Value] {
continue
}
out = append(out, tz)
}
return out
}
// OccurrencesIn returns, for every calendar day (formatted with layout
// "2006-01-02", in loc) in [gridStart, gridEnd] that the series occupies,
// the single VEVENT representing the series on that day. The recurring
// base (RRULE expansion) supplies the day's event, but an explicit
// instance on the same day takes precedence (Exchange's "override" model:
// this is how per-instance edits and "Canceled:" entries replace the
// series occurrence for that day). At most one event per day is ever
// returned, so callers can paint exactly one grid cell per day.
func (s *Series) OccurrencesIn(gridStart, gridEnd time.Time, loc *time.Location) map[string]ical.Event {
const layout = "2006-01-02"
out := make(map[string]ical.Event)
note := func(t0 time.Time, ev ical.Event) {
out[t0.In(loc).Format(layout)] = ev
}
if s.Base != nil {
if rset, err := s.Base.RecurrenceSet(loc); err == nil && rset != nil {
for _, occ := range rset.Between(gridStart, gridEnd, true) {
note(occ, *s.Base)
}
}
}
for i := range s.Instances {
dtp := s.Instances[i].Props.Get(ical.PropDateTimeStart)
if dtp == nil {
continue
}
t0, err := dtp.DateTime(loc)
if err != nil || t0.Before(gridStart) || t0.After(gridEnd) {
continue
}
note(t0, s.Instances[i])
}
return out
}
// dtStartEarlier reports whether a's DTSTART value sorts before b's
// (string compare of the raw property value is sufficient for a
// deterministic tie-break used by Anchor).
func dtStartEarlier(a, b ical.Event) bool {
av := a.Props.Get(ical.PropDateTimeStart)
bv := b.Props.Get(ical.PropDateTimeStart)
switch {
case av == nil:
return false
case bv == nil:
return true
}
return av.Value < bv.Value
}
// EventID returns a stable, short identifier for a single ical.Event,
// suitable for use as a filesystem object name or URL path segment. It is
// the first 32 hex chars (128 bits) of
// sha256("<DTSTART-value>|<duration>|<SUMMARY>") with a ".ics" suffix.
//
// Two events with the same DTSTART, same duration, and same SUMMARY hash
// to the same ID — this matches the addressing scheme used both by the
// web detail view and the CalDAV backend for ICS-subscription events.
// Returns "" if DTSTART is missing (not addressable).
func EventID(ev ical.Event) string {
start := ev.Props.Get(ical.PropDateTimeStart)
if start == nil {
return ""
}
dur := ""
if end := ev.Props.Get(ical.PropDateTimeEnd); end != nil {
if s, err := start.DateTime(time.UTC); err == nil {
if e, err := end.DateTime(time.UTC); err == nil {
dur = e.Sub(s).Round(time.Second).String()
}
}
}
summary := ""
if p := ev.Props.Get(ical.PropSummary); p != nil {
summary = p.Value
}
var keyBuf strings.Builder
keyBuf.WriteString(start.Value)
keyBuf.WriteRune('|')
keyBuf.WriteString(dur)
keyBuf.WriteRune('|')
keyBuf.WriteString(summary)
sum := sha256.Sum256([]byte(keyBuf.String()))
return hex.EncodeToString(sum[:16]) + ".ics"
}
+469
View File
@@ -0,0 +1,469 @@
package icssub
import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
ical "github.com/emersion/go-ical"
)
const sampleICS = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:ev1@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260805T090000Z\r\n" +
"DTEND:20260805T100000Z\r\n" +
"SUMMARY:Original title\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
func mustParseEvent(raw string) ical.Event {
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
if err != nil {
panic("mustParseEvent: " + err.Error())
}
evs := cal.Events()
if len(evs) == 0 {
panic("mustParseEvent: no events")
}
return evs[0]
}
// TestCacheFirstFetchPopulatesEntry verifies that the very first Get for a
// URL does a foreground fetch and returns the parsed calendar.
func TestCacheFirstFetchPopulatesEntry(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(sampleICS))
}))
defer srv.Close()
c := NewCache(time.Hour)
cal, err := c.Get(srv.URL)
if err != nil {
t.Fatalf("first Get: %v", err)
}
if len(cal.Events()) == 0 {
t.Fatalf("expected >=1 event, got 0")
}
}
// TestCacheStaleReturnsWithBackgroundRefresh verifies that once a cached
// entry is stale, Get keeps returning the *stale* copy immediately while a
// background refresh is spawned in a separate goroutine (rather than
// blocking the caller on the network).
func TestCacheStaleReturnsWithBackgroundRefresh(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
time.Sleep(50 * time.Millisecond) // make the fetch slow enough to
w.WriteHeader(http.StatusOK) // observe as background work
_, _ = w.Write([]byte(sampleICS))
}))
defer srv.Close()
c := NewCache(1 * time.Millisecond) // very short TTL
if _, err := c.Get(srv.URL); err != nil {
t.Fatalf("first Get: %v", err)
}
firstHits := hits.Load()
// Force staleness.
time.Sleep(3 * time.Millisecond)
// Subsequent Get must return the stale copy immediately without waiting
// for the slow server to respond — if it blocked, this call would take
// >= 50ms, which we bound with a deadline below via the hit counter.
st := time.Now()
cal, err := c.Get(srv.URL)
if err != nil {
t.Fatalf("second Get: %v", err)
}
if len(cal.Events()) == 0 {
t.Fatalf("expected event in stale response")
}
if time.Since(st) > 40*time.Millisecond {
t.Fatalf("second Get appears to have blocked on the network for %v", time.Since(st))
}
// Wait for the background refresh to complete.
deadline := time.Now().Add(2 * time.Second)
for hits.Load() == firstHits && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if hits.Load() == firstHits {
t.Fatalf("background refresh did not fire (hits stayed at %d)", firstHits)
}
}
// TestCacheConcurrentFirstFetchCoalesce ensures N concurrent first calls
// for the same URL coalesce to a small number of actual origin fetches.
func TestCacheConcurrentFirstFetchCoalesce(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
time.Sleep(40 * time.Millisecond) // widen the coalescing window
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(sampleICS))
}))
defer srv.Close()
c := NewCache(time.Hour)
const n = 8
errs := make([]error, n)
var wg sync.WaitGroup
start := make(chan struct{})
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
<-start
_, err := c.Get(srv.URL)
errs[i] = err
}(i)
}
close(start)
wg.Wait()
for _, err := range errs {
if err != nil {
t.Fatalf("goroutine error: %v", err)
}
}
// Without coalescing we'd see n=8 hits; with it we expect a small
// constant (the first caller fetches; the rest either return the
// in-progress result or kick off a coalesced background refresh).
if hits.Load() > 3 {
t.Fatalf("expected coalescing to reduce fetches (got %d)", hits.Load())
}
}
// TestEventIDStable verifies that the same event hashes to the same ID
// across calls, and is the right shape (32 hex chars + ".ics").
func TestEventIDStable(t *testing.T) {
ev := mustParseEvent(sampleICS)
id1 := EventID(ev)
id2 := EventID(ev)
if id1 != id2 {
t.Fatalf("EventID not stable: %q vs %q", id1, id2)
}
if !strings.HasSuffix(id1, ".ics") {
t.Fatalf("EventID should end in .ics, got %q", id1)
}
if len(id1) != 32+4 {
t.Fatalf("expected 32 hex chars + .ics, got %q (len %d)", id1, len(id1))
}
}
// TestEventIDDiffersForDifferentEvents verifies that two events with
// different titles or different start times hash to different IDs, while
// two events with only a different UID hash to the same ID.
func TestEventIDDiffersForDifferentEvents(t *testing.T) {
base := EventID(mustParseEvent(sampleICS))
// Different title.
rawA := strings.Replace(sampleICS, "SUMMARY:Original title", "SUMMARY:Other title", 1)
if EventID(mustParseEvent(rawA)) == base {
t.Fatal("same start, different title must hash differently")
}
// Different start time.
rawB := strings.Replace(sampleICS, "DTSTART:20260805T090000Z", "DTSTART:20260806T090000Z", 1)
if EventID(mustParseEvent(rawB)) == base {
t.Fatal("different start times must hash differently")
}
// Same start, same title, different UID → same hash.
rawC := strings.Replace(sampleICS, "UID:ev1@nidus.test", "UID:ev2@nidus.test", 1)
if EventID(mustParseEvent(rawC)) != base {
t.Fatal("UID should not affect the hash — same start/dur/title must be equal")
}
}
// TestEventIDWorksWithoutUID verifies EventID still produces a value (from
// DTSTART+DTEND+SUMMARY) when the event has no UID property.
func TestEventIDWorksWithoutUID(t *testing.T) {
raw := strings.Replace(sampleICS, "UID:ev1@nidus.test\r\n", "", 1)
ev := mustParseEvent(raw)
id := EventID(ev)
if id == "" {
t.Fatal("EventID should be non-empty even without UID")
}
}
// outlookStyleSeries mimics the canonical Outlook/Exchange shape: one UID
// carrying a base VEVENT (with RRULE) plus bare per-occurrence instance
// VEVENTs (the "fully expanded" ICS model). GroupSeries must fold all of
// them into ONE Series (base + 2 instances), not two separate entities.
const outlookStyleSeries = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:series@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260306T103000Z\r\n" +
"DTEND:20260306T113000Z\r\n" +
"RRULE:FREQ=WEEKLY;UNTIL=20260903T083000Z;INTERVAL=3;BYDAY=FR;WKST=SU\r\n" +
"SUMMARY:#smarttouch Planning\r\n" +
"END:VEVENT\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:series@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260320T103000Z\r\n" +
"DTEND:20260320T113000Z\r\n" +
"SUMMARY:#smarttouch Planning\r\n" +
"END:VEVENT\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:series@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260403T103000Z\r\n" +
"DTEND:20260403T123000Z\r\n" +
"SUMMARY:#smarttouch Planning (extended)\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
func TestGroupSeriesFoldsOutlookSeriesShape(t *testing.T) {
cal, err := ical.NewDecoder(strings.NewReader(outlookStyleSeries)).Decode()
if err != nil {
t.Fatal(err)
}
if got := len(cal.Events()); got != 3 {
t.Fatalf("fixture must have 3 VEVENTs, got %d", got)
}
series := GroupSeries(cal)
if len(series) != 1 {
t.Fatalf("GroupSeries: expected 1 series, got %d", len(series))
}
s := series[0]
if s.Base == nil {
t.Fatal("the base (RRULE) VEVENT must be the series Base")
}
if s.Base.Props.Get(ical.PropUID).Value != "series@nidus.test" {
t.Fatalf("wrong base UID: %q", s.Base.Props.Get(ical.PropUID).Value)
}
if len(s.Instances) != 2 {
t.Fatalf("expected 2 explicit instances, got %d", len(s.Instances))
}
if s.ID() == "" {
t.Fatal("series ID must be non-empty")
}
// Anchor must be the base.
if got := s.Anchor().Props.Get(ical.PropUID).Value; got != "series@nidus.test" {
t.Fatalf("Anchor must be the base, got UID %q", got)
}
// Calendar() must contain all three VEVENTs.
if got := s.Calendar().Events(); len(got) != 3 {
t.Fatalf("Calendar() must contain 3 events, got %d", len(got))
}
}
// tzAwareSeries mimics a real Outlook/Exchange feed (already run through
// icalfix.NormalizeTimeZones, hence "Europe/Berlin" rather than the raw
// Windows zone name): a VCALENDAR with one VTIMEZONE the events actually
// reference, plus a second, unrelated VTIMEZONE no event references.
const tzAwareSeries = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:Europe/Berlin\r\n" +
"END:VTIMEZONE\r\n" +
"BEGIN:VTIMEZONE\r\n" +
"TZID:America/New_York\r\n" +
"END:VTIMEZONE\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:tz-series@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART;TZID=Europe/Berlin:20260910T100000\r\n" +
"DTEND;TZID=Europe/Berlin:20260910T110000\r\n" +
"RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=WE\r\n" +
"SUMMARY:Frontend Weekly\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
// TestSeriesCalendarEmbedsReferencedTimezone is the regression test for
// the bug report "Frontend Weekly / Abstimmung Next-Release Package /
// Prd-Deployment don't show up in the CalDAV client": Series.Calendar()
// used to build a VTIMEZONE-less VCALENDAR for every ICS-subscription
// series, even though its VEVENTs' DTSTART/DTEND still carried a
// TZID=Europe/Berlin parameter — an RFC 5545 §3.6.5 violation that made
// strict clients (notably ical4j, which DAVx5 is built on) fail to
// resolve the timezone for recurrence-rule expansion, silently dropping
// the whole (recurring) VEVENT from sync. The fix must embed exactly the
// VTIMEZONE(s) the series' own VEVENTs reference — no more, no less.
func TestSeriesCalendarEmbedsReferencedTimezone(t *testing.T) {
cal, err := ical.NewDecoder(strings.NewReader(tzAwareSeries)).Decode()
if err != nil {
t.Fatal(err)
}
series := GroupSeries(cal)
if len(series) != 1 {
t.Fatalf("expected 1 series, got %d", len(series))
}
out := series[0].Calendar()
var tzids []string
for _, child := range out.Children {
if child.Name == ical.CompTimezone {
tzids = append(tzids, child.Props.Get(ical.PropTimezoneID).Value)
}
}
if len(tzids) != 1 || tzids[0] != "Europe/Berlin" {
t.Fatalf("expected exactly the referenced VTIMEZONE (Europe/Berlin) to be embedded, got %v", tzids)
}
// Re-encoding and re-decoding must round-trip: the VEVENT's DTSTART
// TZID must resolve to a VTIMEZONE actually present in the same
// object (this is what a strict client like ical4j checks).
if got := len(out.Events()); got != 1 {
t.Fatalf("expected 1 VEVENT in the series calendar, got %d", got)
}
}
// twoDistinctSeries are two completely unrelated events (different UIDs).
// GroupSeries must NOT fold them together.
const twoDistinctSeries = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:a@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260809T090000Z\r\n" +
"DTEND:20260809T100000Z\r\n" +
"SUMMARY:meeting A\r\n" +
"END:VEVENT\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:b@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260809T110000Z\r\n" +
"DTEND:20260809T120000Z\r\n" +
"SUMMARY:meeting B\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
func TestGroupSeriesKeepsDistinctSeries(t *testing.T) {
cal, err := ical.NewDecoder(strings.NewReader(twoDistinctSeries)).Decode()
if err != nil {
t.Fatal(err)
}
if got := len(GroupSeries(cal)); got != 2 {
t.Fatalf("two distinct UIDs must produce two series, got %d", got)
}
}
// seriesOnlyInstances is the shape of a set of one-off events on one UID
// with no RRULE. The earliest instance must anchor the series.
const seriesOnlyInstances = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:g@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260810T090000Z\r\n" +
"DTEND:20260810T100000Z\r\n" +
"SUMMARY:later\r\n" +
"END:VEVENT\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:g@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260809T090000Z\r\n" +
"DTEND:20260809T100000Z\r\n" +
"SUMMARY:earlier\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
func TestGroupSeriesAnchorWithoutBase(t *testing.T) {
cal, err := ical.NewDecoder(strings.NewReader(seriesOnlyInstances)).Decode()
if err != nil {
t.Fatal(err)
}
series := GroupSeries(cal)
if len(series) != 1 {
t.Fatalf("expected 1 series, got %d", len(series))
}
s := series[0]
if s.Base != nil {
t.Fatalf("no event carries RRULE, so Base must be nil, got %v", s.Base)
}
if len(s.Instances) != 2 {
t.Fatalf("expected 2 instances, got %d", len(s.Instances))
}
anchor := s.Anchor()
if anchor == nil {
t.Fatal("Anchor must be non-nil for a non-empty series")
}
sp := anchor.Props.Get(ical.PropSummary)
if sp == nil || sp.Value != "earlier" {
t.Fatalf("Anchor should be the earliest instance, got %v", sp)
}
}
// TestSeriesOccurrencesInReturnsOneDayPerDay verifies the crux of the
// web-grid fix: on a day the RRULE base covers AND an explicit instance
// covers, OccurrencesIn returns exactly one event for that day (the
// instance, which "wins" per the Exchange override model), and does not
// double-paint.
func TestSeriesOccurrencesInReturnsOneDayPerDay(t *testing.T) {
cal, err := ical.NewDecoder(strings.NewReader(outlookStyleSeries)).Decode()
if err != nil {
t.Fatal(err)
}
series := GroupSeries(cal)
if len(series) != 1 {
t.Fatalf("expected 1 series, got %d", len(series))
}
s := series[0]
loc := time.UTC
// Window that contains 2026-03-20 (which is both an RRULE date and a
// separate explicit instance in the fixture).
gs := time.Date(2026, 3, 1, 0, 0, 0, 0, loc)
ge := time.Date(2026, 4, 10, 0, 0, 0, 0, loc)
occ := s.OccurrencesIn(gs, ge, loc)
if len(occ) < 3 {
t.Fatalf("expected at least 3 days of occurrences, got %d: %v", len(occ), keysOf(occ))
}
// The explicit instance on 2026-03-20 (title "#smarttouch Planning")
// must be the representative event for that day (the base also covers
// that day via RRULE — but the instance wins).
evOnMar20, ok := occ["2026-03-20"]
if !ok {
t.Fatalf("2026-03-20 is in the window AND is an explicit instance — must be present, got %v", keysOf(occ))
}
if p := evOnMar20.Props.Get(ical.PropSummary); p == nil || p.Value != "#smarttouch Planning" {
t.Fatalf("instance on 2026-03-20 should win over the base; got %v", p)
}
// 2026-04-03 has an explicit instance with a different title — should
// be that title (not the base title) for that day.
evOnApr3, ok := occ["2026-04-03"]
if !ok {
t.Fatalf("2026-04-03 must be present, got %v", keysOf(occ))
}
if p := evOnApr3.Props.Get(ical.PropSummary); p == nil || p.Value != "#smarttouch Planning (extended)" {
t.Fatalf("instance on 2026-04-03 should have the overridden title; got %v", p)
}
// 2026-03-06 is the RRULE base's DTSTART and NOT explicitly overridden —
// the base should be the representative for that day.
evOnBase, ok := occ["2026-03-06"]
if !ok {
t.Fatalf("2026-03-06 (base DTSTART) must be present, got %v", keysOf(occ))
}
if p := evOnBase.Props.Get(ical.PropSummary); p == nil || p.Value != "#smarttouch Planning" {
t.Fatalf("base should represent 2026-03-06; got %v", p)
}
}
func keysOf(m map[string]ical.Event) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
+215 -60
View File
@@ -18,6 +18,8 @@ import (
"git.arnef.de/arnef/nidus/internal/birthdays" "git.arnef.de/arnef/nidus/internal/birthdays"
"git.arnef.de/arnef/nidus/internal/db" "git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icalfix" "git.arnef.de/arnef/nidus/internal/icalfix"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store"
"git.arnef.de/arnef/nidus/internal/web/templates" "git.arnef.de/arnef/nidus/internal/web/templates"
ical "github.com/emersion/go-ical" ical "github.com/emersion/go-ical"
) )
@@ -294,9 +296,9 @@ func parseWeekStart(r *http.Request) time.Time {
// buildMonthView loads every event from every calendar visible to // buildMonthView loads every event from every calendar visible to
// username (own + shared), then places each occurrence's days onto a // username (own + shared), then places each occurrence's days onto a
// 6-week grid covering the requested month (plus enough leading/trailing // 6-week grid covering the requested month (plus enough leading/trailing
// days of neighboring months to fill full weeks). Recurring events // days of neighboring months to fill full weeks). Recurring events (RRULE)
// (RRULE) are not expanded — only an event's own DTSTART/DTEND span is // are expanded: every occurrence falling in the grid's window is placed
// considered. // (see eventOccurrenceDays), not just the event's base DTSTART/DTEND.
func (s *Server) buildMonthView(username string, year int, month time.Month) (templates.MonthViewData, error) { func (s *Server) buildMonthView(username string, year int, month time.Month) (templates.MonthViewData, error) {
loc := time.Local loc := time.Local
first := time.Date(year, month, 1, 0, 0, 0, 0, loc) first := time.Date(year, month, 1, 0, 0, 0, 0, loc)
@@ -471,33 +473,24 @@ func (s *Server) collectCalendarEvents(username string, gridStart, gridEnd time.
if err != nil { if err != nil {
continue continue
} }
form, err := eventFormFromICS(id, data) ev, err := firstEventFromICS(data)
if err != nil { if err != nil {
s.logger.Warn("decoding calendar object", "calendar", entry.Name, "id", id, "error", err) s.logger.Warn("decoding calendar object", "calendar", entry.Name, "id", id, "error", err)
continue continue
} }
startDay, endDay, err := eventDayRange(form, loc) daysSet := eventOccurrenceDays(ev, gridStart, gridEnd, loc, dayIndex)
if len(daysSet) == 0 {
continue
}
form, err := eventFormFromComponent(id, ev)
if err != nil { if err != nil {
continue continue
} }
if endDay.Before(gridStart) || startDay.After(gridEnd) { timeText := ""
continue if !form.AllDay {
timeText = form.StartTime
} }
if startDay.Before(gridStart) { for idx := range daysSet {
startDay = gridStart
}
if endDay.After(gridEnd) {
endDay = gridEnd
}
for d, n := startDay, 0; !d.After(endDay) && n < totalDays; d, n = d.AddDate(0, 0, 1), n+1 {
idx, ok := dayIndex[d.Format(dateLayout)]
if !ok {
continue
}
timeText := ""
if !form.AllDay {
timeText = form.StartTime
}
days[idx].Events = append(days[idx].Events, templates.EventSummary{ days[idx].Events = append(days[idx].Events, templates.EventSummary{
ID: id, ID: id,
CalRef: entry.Ref, CalRef: entry.Ref,
@@ -527,25 +520,76 @@ func mondayOf(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).AddDate(0, 0, -offset) return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).AddDate(0, 0, -offset)
} }
// eventDayRange returns the inclusive [start, end] calendar-day span an // eventOccurrenceDays returns the set of grid day indices (into
// event occupies, in loc, for placing it on the month grid. // dayIndex) that event ev occupies within [gridStart, gridEnd]. A plain
func eventDayRange(form templates.EventFormData, loc *time.Location) (start, end time.Time, err error) { // event occupies its DTSTART..DTEND day span. A recurring event (RRULE)
start, err = time.ParseInLocation(dateLayout, form.StartDate, loc) // occupies the day span of each occurrence whose expansion falls in the
// window, so e.g. a weekly meeting is painted on every in-grid weekly date
// rather than only its original date. EXDATE/RDATE are honored via
// go-ical's RecurrenceSet. Only indices for days actually in the grid are
// returned; occurrences entirely outside the window paint nothing.
func eventOccurrenceDays(ev ical.Event, gridStart, gridEnd time.Time, loc *time.Location, dayIndex map[string]int) map[int]bool {
out := make(map[int]bool)
addDay := func(day time.Time) {
day = day.In(loc)
if idx, ok := dayIndex[day.Format(dateLayout)]; ok {
out[idx] = true
}
}
startProp := ev.Props.Get(ical.PropDateTimeStart)
if startProp == nil {
return nil
}
baseStart, err := startProp.DateTime(loc)
if err != nil { if err != nil {
return time.Time{}, time.Time{}, err return nil
} }
endDate := form.EndDate
if endDate == "" { // Per-occurrence duration: the DTSTART..DTEND span of the base event
endDate = form.StartDate // (all-day events with only DTEND=DTSTART+1 give a 1-day span; timed
// events give their hour span). Recurrence preserves the duration.
dur := time.Duration(0)
if endProp := ev.Props.Get(ical.PropDateTimeEnd); endProp != nil {
if baseEnd, err := endProp.DateTime(loc); err == nil {
dur = baseEnd.Sub(baseStart)
}
} }
end, err = time.ParseInLocation(dateLayout, endDate, loc)
spread := func(start time.Time) {
end := start.Add(dur)
for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
addDay(d)
if len(out) == len(dayIndex) {
return
}
}
}
if rset, rerr := ev.RecurrenceSet(loc); rerr == nil && rset != nil {
for _, occ := range rset.Between(gridStart, gridEnd, true) {
spread(occ)
}
} else {
spread(baseStart)
}
return out
}
// firstEventFromICS decodes data (a single-VEVENT calendar object) and
// returns its first VEVENT, for grid placement (which needs the raw
// ical.Event so recurring events can be expanded, see
// eventOccurrenceDays).
func firstEventFromICS(data []byte) (ical.Event, error) {
calendar, err := ical.NewDecoder(bytes.NewReader(icalfix.NormalizeTimeZones(data))).Decode()
if err != nil { if err != nil {
return time.Time{}, time.Time{}, err return ical.Event{}, err
} }
if end.Before(start) { events := calendar.Events()
end = start if len(events) == 0 {
return ical.Event{}, fmt.Errorf("no VEVENT in calendar object")
} }
return start, end, nil return events[0], nil
} }
func (s *Server) handleEventNew(w http.ResponseWriter, r *http.Request) { func (s *Server) handleEventNew(w http.ResponseWriter, r *http.Request) {
@@ -636,6 +680,113 @@ func newEventFormDefaults(calRef, dateParam string) templates.EventFormData {
} }
} }
// handleEventView renders the read-only detail view for a single event. It
// is the landing page when a user clicks an event in the month/week grid;
// writable calendars link from here to the edit page.
func (s *Server) handleEventView(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
username := userFromContext(r.Context())
ref := r.PathValue("ref")
id := r.PathValue("id")
// For ICS subscriptions, ref is "!<name>" and id is the stable
// icssub.EventID (already ".ics"-suffixed). For regular calendars,
// ref is a bare name or "owner~name" and id is a "<hex>.ics" filename
// from the eventIDRe character set. Both shapes share the same
// "hex/alnum .ics" shape, so we only need the regex check.
if !eventIDRe.MatchString(id) {
http.NotFound(w, r)
return
}
color, form, err := s.eventForDisplay(username, ref, id)
if errors.Is(err, store.ErrNotFound) || errors.Is(err, errCalendarNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.handleCalRefError(w, r, err)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = templates.EventDetail(username, templates.EventDetailData{Form: form, Color: color}).Render(context.Background(), w)
}
// eventForDisplay resolves a calendar reference for read access, loads and
// decodes the event with the given id, populates the form's display fields
// (CalRef, CalendarLabel, Writable), and returns the calendar's color for
// the detail view's header dot. It handles both ordinary (stored) events
// and ICS-subscription events (ref "!<name>").
func (s *Server) eventForDisplay(username, ref, id string) (color string, form templates.EventFormData, err error) {
if strings.HasPrefix(ref, icsRefPrefix) {
return s.icsEventForDisplay(username, ref, id)
}
owner, name, err := s.resolveCalRef(username, ref, false)
if err != nil {
return "", form, err
}
data, err := s.store.GetObject(owner, "cal-"+name, id)
if err != nil {
return "", form, err
}
form, err = eventFormFromICS(id, data)
if err != nil {
s.logger.Error("decoding event", "error", err)
return "", form, err
}
form.CalRef = ref
label := name
if owner != username {
label = name + " (" + s.dbase.DisplayName(owner) + ")"
}
form.CalendarLabel = label
form.Writable = owner == username
if !form.Writable {
if share, err := s.dbase.CalendarShareFor(owner, name, username); err == nil {
form.Writable = share.Permission == db.PermWrite
}
}
color, _ = s.dbase.GetCalendarColor(owner, name)
return color, form, nil
}
// icsEventForDisplay resolves one of username's ICS subscriptions named
// ref[len(!):] and looks up the Series whose icssub ID matches id, then
// returns the subscription's display color and a form (Writable=false)
// summarizing the series' anchor event (base, or earliest instance).
func (s *Server) icsEventForDisplay(username, ref, id string) (color string, form templates.EventFormData, err error) {
name := strings.TrimPrefix(ref, icsRefPrefix)
sub, err := s.dbase.GetICSSubscription(username, name)
if err != nil {
return "", form, errCalendarNotFound
}
cal, err := s.icsCache.Get(sub.URL)
if err != nil {
return "", form, err
}
for _, series := range icssub.GroupSeries(cal) {
if series.Base == nil && len(series.Instances) == 0 {
continue
}
if series.ID() != id {
continue
}
anchor := series.Anchor()
form, err = eventFormFromComponent(id, *anchor)
if err != nil {
return "", form, err
}
form.CalRef = ref
form.CalendarLabel = name
form.Writable = false
return sub.Color, form, nil
}
return "", form, errCalendarNotFound
}
func (s *Server) handleEventEdit(w http.ResponseWriter, r *http.Request) { func (s *Server) handleEventEdit(w http.ResponseWriter, r *http.Request) {
username := userFromContext(r.Context()) username := userFromContext(r.Context())
ref := r.PathValue("ref") ref := r.PathValue("ref")
@@ -1199,42 +1350,47 @@ func (s *Server) addBirthdayEvents(username string, entry calendarEntry, gridSta
} }
// addICSEvents fetches entry's remote ICS/webcal calendar (via s.icsCache, // addICSEvents fetches entry's remote ICS/webcal calendar (via s.icsCache,
// which caches it for a while so every month-view render doesn't re-fetch // which uses stale-while-revalidate so a month-view render never blocks on
// from origin) and places each VEVENT's occurrence onto the month grid, // network I/O) and places each Series' day-occurrences onto the grid.
// the same way a stored calendar object would be. There's no per-event //
// edit page for these (the source is external and read-only), so each // A "Series" is one UID group in the feed: the base (RRULE-carrying)
// event's LinkURL is left pointing nowhere useful ("#"). // VEVENT plus any explicit per-occurrence instances. OccurrencesIn
// collapses them to one event per (series, day), so a day the base RRULE
// covers AND an explicit instance covers is painted once, with the
// instance winning (Exchange's "override" model — this is how "Canceled:"
// entries replace the base occurrence for that day).
func (s *Server) addICSEvents(entry calendarEntry, gridStart, gridEnd time.Time, loc *time.Location, dayIndex map[string]int, days []templates.MonthDay) error { func (s *Server) addICSEvents(entry calendarEntry, gridStart, gridEnd time.Time, loc *time.Location, dayIndex map[string]int, days []templates.MonthDay) error {
cal, err := s.icsCache.Get(entry.ICSURL) cal, err := s.icsCache.Get(entry.ICSURL)
if err != nil { if err != nil {
return err return err
} }
const totalDays = 42 for _, series := range icssub.GroupSeries(cal) {
for i, ev := range cal.Events() { if series.Base == nil && len(series.Instances) == 0 {
id := fmt.Sprintf("ics-%d", i) continue
form, err := eventFormFromComponent(id, ev) }
id := series.ID()
occByDay := series.OccurrencesIn(gridStart, gridEnd, loc)
if len(occByDay) == 0 {
continue
}
anchor := series.Anchor()
baseForm, err := eventFormFromComponent(id, *anchor)
if err != nil { if err != nil {
continue continue
} }
startDay, endDay, err := eventDayRange(form, loc) for dayStr, ev := range occByDay {
if err != nil { idx, ok := dayIndex[dayStr]
continue
}
if endDay.Before(gridStart) || startDay.After(gridEnd) {
continue
}
if startDay.Before(gridStart) {
startDay = gridStart
}
if endDay.After(gridEnd) {
endDay = gridEnd
}
for d, n := startDay, 0; !d.After(endDay) && n < totalDays; d, n = d.AddDate(0, 0, 1), n+1 {
idx, ok := dayIndex[d.Format(dateLayout)]
if !ok { if !ok {
continue continue
} }
// Per-day data: the day's own summary (an explicit instance
// may override the base's — "Canceled: X" or a per-instance
// title change). Fall back to the base summary otherwise.
form := baseForm
if ps := ev.Props.Get(ical.PropSummary); ps != nil && ps.Value != "" {
form.Summary = ps.Value
}
timeText := "" timeText := ""
if !form.AllDay { if !form.AllDay {
timeText = form.StartTime timeText = form.StartTime
@@ -1246,7 +1402,6 @@ func (s *Server) addICSEvents(entry calendarEntry, gridStart, gridEnd time.Time,
Summary: form.Summary, Summary: form.Summary,
TimeText: timeText, TimeText: timeText,
AllDay: form.AllDay, AllDay: form.AllDay,
LinkURL: "#",
}) })
} }
} }
+24 -1
View File
@@ -14,7 +14,9 @@ import (
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"time"
"git.arnef.de/arnef/nidus/internal/birthdays"
"git.arnef.de/arnef/nidus/internal/store" "git.arnef.de/arnef/nidus/internal/store"
"git.arnef.de/arnef/nidus/internal/web/templates" "git.arnef.de/arnef/nidus/internal/web/templates"
vcard "github.com/emersion/go-vcard" vcard "github.com/emersion/go-vcard"
@@ -490,6 +492,27 @@ func photoDataURL(card vcard.Card) string {
return "" return ""
} }
// birthdayInputValue returns birthday in the "YYYY-MM-DD" form the contact
// form's <input type="date"> renders. vCards from other clients often store
// the date in vCard 3.0's compact "YYYYMMDD" form or year-less "--MMDD"
// form; a browser date input silently ignores values it can't parse, which
// would leave the field looking empty and drop the birthday on the next
// save. A year-less value can't be shown in a year-bearing date input as-is,
// so it's pre-filled with the current year — the field still shows the
// contact's real month/day (never the blank state the bug produced), and the
// user can correct the year if they know it. Unrecognized values pass
// through unchanged (the empty string for contacts without a birthday).
func birthdayInputValue(birthday string) string {
month, day, year, ok := birthdays.ParseBirthday(birthday)
if !ok {
return birthday
}
if year == 0 {
year = time.Now().Year()
}
return fmt.Sprintf("%04d-%02d-%02d", year, int(month), day)
}
func labeledValues(card vcard.Card, key string) []templates.LabeledValue { func labeledValues(card vcard.Card, key string) []templates.LabeledValue {
fields := card[key] fields := card[key]
out := make([]templates.LabeledValue, 0, len(fields)) out := make([]templates.LabeledValue, 0, len(fields))
@@ -541,7 +564,7 @@ func contactFormFromCard(book, id string, data []byte) (templates.ContactFormDat
Surname: surname, Surname: surname,
Organization: card.PreferredValue(vcard.FieldOrganization), Organization: card.PreferredValue(vcard.FieldOrganization),
Note: card.PreferredValue(vcard.FieldNote), Note: card.PreferredValue(vcard.FieldNote),
Birthday: card.PreferredValue(vcard.FieldBirthday), Birthday: birthdayInputValue(card.PreferredValue(vcard.FieldBirthday)),
PhotoDataURL: photoDataURL(card), PhotoDataURL: photoDataURL(card),
Phones: ensureAtLeastOne(labeledValues(card, vcard.FieldTelephone)), Phones: ensureAtLeastOne(labeledValues(card, vcard.FieldTelephone)),
Emails: ensureAtLeastOne(labeledValues(card, vcard.FieldEmail)), Emails: ensureAtLeastOne(labeledValues(card, vcard.FieldEmail)),
+209
View File
@@ -0,0 +1,209 @@
package web
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"git.arnef.de/arnef/nidus/internal/db"
)
// seedEvent stores an all-day event (one-day span) in owner's calendar cal
// under object id, with the given summary/location/description. Used to set
// up events that handleEventView should render.
func seedEvent(t *testing.T, s *Server, owner, cal, id, summary, location, description string) {
t.Helper()
data := "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:" + strings.TrimSuffix(id, ".ics") + "\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"SUMMARY:" + summary + "\r\n" +
"LOCATION:" + location + "\r\n" +
"DESCRIPTION:" + description + "\r\n" +
"DTSTART;VALUE=DATE:20260805\r\n" +
"DTEND;VALUE=DATE:20260806\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
if err := s.store.PutObject(owner, "cal-"+cal, id, []byte(data)); err != nil {
t.Fatalf("PutObject: %v", err)
}
}
// getEventDetail issues GET /calendar/{ref}/{id} as the session identified by
// cookie and returns the recorded response.
func getEventDetail(t *testing.T, handler http.Handler, cookie *http.Cookie, ref, id string) *httptest.ResponseRecorder {
t.Helper()
path := "/calendar/" + url.PathEscape(ref) + "/" + url.PathEscape(id)
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
return rr
}
func TestEventDetailShowsOwnEvent(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
id := "aabbccddeeff.ics"
seedEvent(t, s, "alice", "work", id, "Team standup", "Meetroom A", "Daily sync with the team")
rr := getEventDetail(t, handler, cookie, "work", id)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
body := rr.Body.String()
for _, want := range []string{
"Team standup", // summary / title
"Meetroom A", // location
"Daily sync with the team", // description
"work", // calendar label
">Edit", // writable → Edit link present
"Export .ics",
} {
if !strings.Contains(body, want) {
t.Errorf("expected body to contain %q, got:\n%s", want, body)
}
}
}
func TestEventDetailReadOnlySharedHasNoEdit(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
aliceCookie := loginAs(t, handler, "alice", "password")
bobCookie := loginAs(t, handler, "bob", "password")
id := "123456.ics"
seedEvent(t, s, "bob", "personal", id, "Bob lunch", "Cafe", "Lunch plans")
if err := s.dbase.ShareCalendar("bob", "personal", "alice", db.PermRead); err != nil {
t.Fatalf("ShareCalendar: %v", err)
}
// alice (read share) can view but not edit.
rr := getEventDetail(t, handler, aliceCookie, "bob~personal", id)
if rr.Code != http.StatusOK {
t.Fatalf("alice view: expected 200, got %d: %s", rr.Code, rr.Body.String())
}
body := rr.Body.String()
if !strings.Contains(body, "Bob lunch") {
t.Errorf("alice: expected body to contain summary, got:\n%s", body)
}
if !strings.Contains(body, "shared with you as read-only") {
t.Errorf("alice: expected read-only notice, got:\n%s", body)
}
if strings.Contains(body, ">Edit") {
t.Errorf("alice: Edit link should not be present on a read-only share, got:\n%s", body)
}
// bob (owner) can still see the Edit link.
rrBob := getEventDetail(t, handler, bobCookie, "personal", id)
if rrBob.Code != http.StatusOK {
t.Fatalf("bob view own: expected 200, got %d", rrBob.Code)
}
if !strings.Contains(rrBob.Body.String(), ">Edit") {
t.Errorf("bob: expected Edit link, got:\n%s", rrBob.Body.String())
}
}
func TestEventDetailWriteShareHasEditLink(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
seedEvent(t, s, "bob", "personal", "a1b2c3.ics", "Bob meeting", "Office", "Sync")
if err := s.dbase.ShareCalendar("bob", "personal", "alice", db.PermWrite); err != nil {
t.Fatalf("ShareCalendar: %v", err)
}
rr := getEventDetail(t, handler, cookie, "bob~personal", "a1b2c3.ics")
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
body := rr.Body.String()
if !strings.Contains(body, ">Edit") {
t.Errorf("write share should expose Edit link, got:\n%s", body)
}
if strings.Contains(body, "shared with you as read-only") {
t.Errorf("write share should not show read-only notice, got:\n%s", body)
}
}
func TestEventDetailNotFound(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
// Valid calendar, missing object.
if rr := getEventDetail(t, handler, cookie, "work", "doesnotexist.ics"); rr.Code != http.StatusNotFound {
t.Fatalf("missing event: expected 404, got %d", rr.Code)
}
// Unknown calendar ref.
if rr := getEventDetail(t, handler, cookie, "does_not_exist", "0000.ics"); rr.Code != http.StatusNotFound {
t.Fatalf("unknown calendar: expected 404, got %d", rr.Code)
}
// Invalid id shape (rejected by eventIDRe before store access).
if rr := getEventDetail(t, handler, cookie, "work", "bad/../etc/passwd.ics"); rr.Code != http.StatusNotFound {
t.Fatalf("invalid id: expected 404, got %d", rr.Code)
}
}
func TestEventDetailRequiresLogin(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
req := httptest.NewRequest(http.MethodGet, "/calendar/work/anything.ics", nil)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Fatalf("expected redirect to login, got %d", rr.Code)
}
}
func TestEventDetailRejectsNonGet(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
req := httptest.NewRequest(http.MethodPost, "/calendar/work/anything.ics", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected 405 for POST, got %d", rr.Code)
}
}
// TestEditRouteStillResolves guards against the new detail route
// (/calendar/{ref}/{id}) shadowing the more specific edit/delete/export
// routes under the same {ref}+{id} prefix in Go's ServeMux.
func TestEditRouteStillResolves(t *testing.T) {
s := newTestServer(t)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
id := "cafebabe00.ics"
seedEvent(t, s, "alice", "work", id, "Edit me", "Room", "Note")
// GET the edit form — must still hit handleEventEdit, not the detail view.
req := httptest.NewRequest(http.MethodGet, "/calendar/work/cafebabe00.ics/edit", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("edit GET: expected 200, got %d: %s", rr.Code, rr.Body.String())
}
if !strings.Contains(rr.Body.String(), "Edit event") || !strings.Contains(rr.Body.String(), "<form") {
t.Fatalf("expected the edit form to render, got:\n%s", rr.Body.String())
}
// The delete route still works (redirect to /web/calendar on success).
req = httptest.NewRequest(http.MethodPost, "/calendar/work/cafebabe00.ics/delete", nil)
req.AddCookie(cookie)
rr = httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusSeeOther {
t.Fatalf("delete: expected 303 redirect, got %d: %s", rr.Code, rr.Body.String())
}
}
+272
View File
@@ -0,0 +1,272 @@
package web
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"time"
"git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store"
ical "github.com/emersion/go-ical"
)
// icsDetailSample is a minimal valid ICS feed with one VEVENT on Aug 5, 2026.
const icsDetailSample = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:detail1@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260805T090000Z\r\n" +
"DTEND:20260805T100000Z\r\n" +
"SUMMARY:ICS detail event\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
// newServerWithICSCache builds a Server wired to an upstream ICS server
// (for deterministic tests) and returns it, sharing one icssub.Cache the
// same way cmd/server/main.go does in production.
func newServerWithICSCache(t *testing.T, upstreamURL string) *Server {
t.Helper()
dir := t.TempDir()
st, err := store.NewStore(filepath.Join(dir, "data"))
if err != nil {
t.Fatalf("NewStore: %v", err)
}
d, err := db.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Open: %v", err)
}
t.Cleanup(func() { d.Close() })
cfg := &config.Config{}
if err := d.CreateUser("alice", "password", "", ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := d.CreateICSSubscription("alice", "holidays", upstreamURL, "#123abc"); err != nil {
t.Fatalf("CreateICSSubscription: %v", err)
}
shared := icssub.NewCache(time.Hour)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(cfg, st, d, logger, shared)
}
// TestICSDetailRouteRendersReadonlyEvent verifies the full ICS detail path:
// the user clicks an ICS event from the month/week grid, the browser lands
// on GET /calendar/!holidays/<icssub.EventID>/, and the handler returns 200
// with the event's fields rendered and NO Edit link (ICS subs are read-only).
func TestICSDetailRouteRendersReadonlyEvent(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsDetailSample))
}))
defer srv.Close()
s := newServerWithICSCache(t, srv.URL)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
id := seriesID(t, icsDetailSample)
if id == "" {
t.Fatal("series ID must be non-empty")
}
req := httptest.NewRequest(http.MethodGet, "/calendar/"+url.PathEscape("!holidays")+"/"+id, nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
body := rr.Body.String()
for _, want := range []string{
"ICS detail event", // summary
"holidays", // calendar label
} {
if !strings.Contains(body, want) {
t.Errorf("expected body to contain %q, got:\n%s", want, body)
}
}
if strings.Contains(body, ">Edit") {
t.Errorf("Edit link should not be present on a read-only ICS detail page, got:\n%s", body)
}
}
// TestICSDetailRouteBadIDReturns404 verifies a request with a malformed
// event ID (missing .ics suffix) gets a 404 rather than rendering.
func TestICSDetailRouteBadIDReturns404(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(icsDetailSample))
}))
defer srv.Close()
s := newServerWithICSCache(t, srv.URL)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
req := httptest.NewRequest(http.MethodGet, "/calendar/!holidays/not-a-valid-id", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusNotFound {
t.Fatalf("expected 404 for malformed event id, got %d", rr.Code)
}
}
// TestMonthGridLinksICSEventToDetailPage exercises the full user path: the
// month/week grid renders an ICS-subscription event as a link to a detail
// page (not "#" and not a direct edit URL).
func TestMonthGridLinksICSEventToDetailPage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(icsDetailSample))
}))
defer srv.Close()
s := newServerWithICSCache(t, srv.URL)
handler := s.Handler(emptyStaticFS{})
cookie := loginAs(t, handler, "alice", "password")
req := httptest.NewRequest(http.MethodGet, "/calendar?year=2026&month=8", nil)
req.AddCookie(cookie)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
}
body := rr.Body.String()
if !strings.Contains(body, "ICS detail event") {
t.Fatalf("month grid should list ICS events, got:\n%s", body)
}
id := seriesID(t, icsDetailSample)
// The grid renders the detail link with a "/web/calendar/!<ref>/<id>"
// shape (see eventLinkURL in calendar.templ). The "!" in the ref is
// not %-escaped by templ.URL — we observed un-escaped output in the
// rendered HTML and pin the exact shape below.
wantHref := "href=\"/web/calendar/!holidays/" + id + "\""
if !strings.Contains(body, wantHref) {
t.Fatalf("month grid should link ICS event to %q, but did not", wantHref)
}
if strings.Contains(body, `href="#"`) {
t.Fatalf("ICS events should not link to '#'")
}
}
// TestEventOccurrenceDaysExpandsRRule verifies that a recurring event
// (RRULE) is placed on every in-window occurrence day, not just its base
// date — the core of the "recurring series events missing" fix.
func TestEventOccurrenceDaysExpandsRRule(t *testing.T) {
const raw = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:rec1@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260803T090000Z\r\n" + // a Monday
"DTEND:20260803T100000Z\r\n" +
"RRULE:FREQ=WEEKLY;COUNT=4\r\n" +
"SUMMARY:weekly meeting\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
ev := mustParseICS(t, raw)
loc := time.UTC
// Window covering the whole of August 2026 (the 4 weekly occurrences:
// Aug 3, 10, 17, 24 are all within range).
gridStart := time.Date(2026, 8, 1, 0, 0, 0, 0, loc)
gridEnd := time.Date(2026, 8, 31, 0, 0, 0, 0, loc)
dayIndex := make(map[string]int)
for d, i := gridStart, 0; !d.After(gridEnd); d, i = d.AddDate(0, 0, 1), i+1 {
dayIndex[d.Format(dateLayout)] = i
}
got := eventOccurrenceDays(ev, gridStart, gridEnd, loc, dayIndex)
wantDates := []string{"2026-08-03", "2026-08-10", "2026-08-17", "2026-08-24"}
for _, ws := range wantDates {
if _, ok := got[dayIndex[ws]]; !ok {
t.Errorf("expected recurring occurrence on %s, got days %v", ws, got)
}
}
if len(got) != 4 {
t.Errorf("expected exactly 4 in-window occurrence days, got %d (%v)", len(got), got)
}
}
// TestEventOccurrenceDaysSingleEvent verifies a non-recurring event occupies
// only its own day(s) (no spurious expansion).
func TestEventOccurrenceDaysSingleEvent(t *testing.T) {
const raw = "BEGIN:VCALENDAR\r\n" +
"VERSION:2.0\r\n" +
"PRODID:-//nidus//test//EN\r\n" +
"BEGIN:VEVENT\r\n" +
"UID:single1@nidus.test\r\n" +
"DTSTAMP:20260101T000000Z\r\n" +
"DTSTART:20260805T090000Z\r\n" +
"DTEND:20260805T100000Z\r\n" +
"SUMMARY:one off\r\n" +
"END:VEVENT\r\n" +
"END:VCALENDAR\r\n"
ev := mustParseICS(t, raw)
loc := time.UTC
gridStart := time.Date(2026, 8, 1, 0, 0, 0, 0, loc)
gridEnd := time.Date(2026, 8, 31, 0, 0, 0, 0, loc)
dayIndex := make(map[string]int)
for d, i := gridStart, 0; !d.After(gridEnd); d, i = d.AddDate(0, 0, 1), i+1 {
dayIndex[d.Format(dateLayout)] = i
}
got := eventOccurrenceDays(ev, gridStart, gridEnd, loc, dayIndex)
if len(got) != 1 {
t.Fatalf("expected exactly 1 occurrence day, got %d (%v)", len(got), got)
}
if _, ok := got[dayIndex["2026-08-05"]]; !ok {
t.Errorf("expected event on 2026-08-05, got days %v", got)
}
}
// seriesID returns the stable ID that addICSEvents/icsEventForDisplay
// advertise for the (single) series in raw — GroupSeries(raw)[0].ID().
// ICS-subscription grid cells and detail links are keyed by the series,
// not by individual VEVENTs, so this is what the href/ID in assertions
// must match.
func seriesID(t *testing.T, raw string) string {
t.Helper()
_ = t
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
if err != nil {
t.Fatalf("seriesID: ical decode: %v", err)
}
series := icssub.GroupSeries(cal)
if len(series) == 0 {
t.Fatal("seriesID: no series")
}
return series[0].ID()
}
// mustParseICS parses raw and returns its first VEVENT (panic on error).
func mustParseICS(t *testing.T, raw string) ical.Event {
t.Helper()
cal, err := ical.NewDecoder(strings.NewReader(raw)).Decode()
if err != nil {
t.Fatalf("ical decode: %v", err)
}
evs := cal.Events()
if len(evs) == 0 {
t.Fatal("no events in ICS")
}
return evs[0]
}
+11 -3
View File
@@ -25,9 +25,16 @@ type Server struct {
icsCache *icssub.Cache icsCache *icssub.Cache
} }
// NewServer constructs a web UI Server. // NewServer constructs a web UI Server. icsCache may be nil, in which
func NewServer(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) *Server { // case a private default-TTL cache is created — prefer sharing a single
return &Server{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icssub.NewCache(icssub.DefaultTTL)} // *icssub.Cache with the CALDAV/CardDAV backends (e.g. from
// cmd/server/main.go) so the web calendar page and the DAV protocol
// serve identical events for the same ICS subscription.
func NewServer(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger, icsCache *icssub.Cache) *Server {
if icsCache == nil {
icsCache = icssub.NewCache(icssub.DefaultTTL)
}
return &Server{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icsCache}
} }
// Handler returns the http.Handler serving the web UI, mounted at "/web/" // Handler returns the http.Handler serving the web UI, mounted at "/web/"
@@ -65,6 +72,7 @@ func (s *Server) Handler(staticFS http.FileSystem) http.Handler {
mux.HandleFunc("/calendar", s.requireLogin(s.handleCalendarMonth)) mux.HandleFunc("/calendar", s.requireLogin(s.handleCalendarMonth))
mux.HandleFunc("/calendar/week", s.requireLogin(s.handleCalendarWeek)) mux.HandleFunc("/calendar/week", s.requireLogin(s.handleCalendarWeek))
mux.HandleFunc("/calendar/new", s.requireLogin(s.handleEventNew)) mux.HandleFunc("/calendar/new", s.requireLogin(s.handleEventNew))
mux.HandleFunc("/calendar/{ref}/{id}", s.requireLogin(s.handleEventView))
mux.HandleFunc("/calendar/{ref}/import", s.requireLogin(s.handleCalendarImport)) mux.HandleFunc("/calendar/{ref}/import", s.requireLogin(s.handleCalendarImport))
mux.HandleFunc("/calendar/{ref}/export", s.requireLogin(s.handleCalendarExportAll)) mux.HandleFunc("/calendar/{ref}/export", s.requireLogin(s.handleCalendarExportAll))
mux.HandleFunc("/calendar/{ref}/{id}/edit", s.requireLogin(s.handleEventEdit)) mux.HandleFunc("/calendar/{ref}/{id}/edit", s.requireLogin(s.handleEventEdit))
+24 -1
View File
@@ -1,6 +1,7 @@
package web package web
import ( import (
"fmt"
"io" "io"
"log/slog" "log/slog"
"net/http" "net/http"
@@ -10,6 +11,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time"
"git.arnef.de/arnef/nidus/internal/config" "git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db" "git.arnef.de/arnef/nidus/internal/db"
@@ -47,7 +49,7 @@ func newTestServer(t *testing.T) *Server {
t.Fatalf("CreateCalendar bob/personal: %v", err) t.Fatalf("CreateCalendar bob/personal: %v", err)
} }
logger := slog.New(slog.NewTextHandler(io.Discard, nil)) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(cfg, st, dbase, logger) return NewServer(cfg, st, dbase, logger, nil)
} }
// loginAs performs a login request against handler and returns the // loginAs performs a login request against handler and returns the
@@ -316,3 +318,24 @@ func TestAccountChangePassword(t *testing.T) {
t.Fatal("expected password to have changed") t.Fatal("expected password to have changed")
} }
} }
func TestBirthdayInputValueNormalizesFormats(t *testing.T) {
year := time.Now().Year()
cases := []struct {
in string
want string
}{
{"", ""},
{"19920217", "1992-02-17"}, // vCard 3.0 compact
{"19540805", "1954-08-05"}, // compact, no VALUE param
{"--0219", fmt.Sprintf("%04d-02-19", year)}, // year-less -> current year
{"2026-09-06", "2026-09-06"}, // already dashed (web-created)
{"1604-02-27", "1604-02-27"}, // dashed, ancient year preserved
{"garbage", "garbage"}, // unrecognized passes through
}
for _, c := range cases {
if got := birthdayInputValue(c.in); got != c.want {
t.Errorf("birthdayInputValue(%q) = %q, want %q", c.in, got, c.want)
}
}
}
+126 -4
View File
@@ -3,6 +3,7 @@ package templates
import "fmt" import "fmt"
import "strconv" import "strconv"
import "strings" import "strings"
import "time"
// CalendarSummary is one calendar (own or shared) shown in the combined // CalendarSummary is one calendar (own or shared) shown in the combined
// month view's legend. // month view's legend.
@@ -24,9 +25,9 @@ type EventSummary struct {
Summary string Summary string
TimeText string // e.g. "14:00" or "" for all-day events TimeText string // e.g. "14:00" or "" for all-day events
AllDay bool AllDay bool
// LinkURL overrides the default "/web/calendar/{CalRef}/{ID}/edit" // LinkURL overrides the default "/web/calendar/{CalRef}/{ID}" (detail
// link target, used by virtual/read-only calendars (e.g. birthdays) // view) link target, used by virtual/read-only calendars (e.g.
// that don't have an editable event object of their own. // birthdays) that don't have an editable event object of their own.
LinkURL string LinkURL string
} }
@@ -100,6 +101,14 @@ type EventFormData struct {
EndTime string // "HH:MM", empty when AllDay EndTime string // "HH:MM", empty when AllDay
} }
// EventDetailData is everything the read-only event detail view needs: the
// decoded event itself (Form, including its ID/CalRef/Writable display
// metadata) plus the calendar's color for the header dot.
type EventDetailData struct {
Form EventFormData
Color string // calendar color, "" if unset
}
templ MonthView(username string, data MonthViewData) { templ MonthView(username string, data MonthViewData) {
@Layout("Calendar", username) { @Layout("Calendar", username) {
<div class="flex items-center justify-between mb-6 gap-4 flex-wrap"> <div class="flex items-center justify-between mb-6 gap-4 flex-wrap">
@@ -301,7 +310,7 @@ func eventLinkURL(ev EventSummary) string {
if ev.LinkURL != "" { if ev.LinkURL != "" {
return ev.LinkURL return ev.LinkURL
} }
return "/web/calendar/" + ev.CalRef + "/" + ev.ID + "/edit" return "/web/calendar/" + ev.CalRef + "/" + ev.ID
} }
// eventTextColor returns a color derived from hex, darkened if needed so // eventTextColor returns a color derived from hex, darkened if needed so
@@ -355,6 +364,119 @@ func clampByte(v float64) int {
// EventDetail is the read-only detail view for a single event, opened when
// the user clicks an event in the month or week grid. It shows the
// event's fields and, when the calendar is writable, offers an Edit link.
templ EventDetail(username string, data EventDetailData) {
@Layout("Calendar", username) {
<div class="flex items-center justify-between gap-3 flex-wrap mb-6">
<a href="/web/calendar" class="text-sm text-indigo-600 hover:underline">&larr; Calendar</a>
<div class="flex items-center gap-3">
if data.Form.Writable {
<a href={ templ.URL("/web/calendar/" + data.Form.CalRef + "/" + data.Form.ID + "/edit") }
class="bg-indigo-600 text-white rounded-md px-3 py-1.5 text-sm font-medium hover:bg-indigo-700">
Edit
</a>
}
<a href={ templ.URL("/web/calendar/" + data.Form.CalRef + "/" + data.Form.ID + "/export") }
class="bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
Export .ics
</a>
</div>
</div>
<div class="bg-white rounded-lg border border-gray-200 p-6 max-w-2xl">
<div class="flex items-start gap-3 border-b border-gray-100 pb-5 mb-5">
<span class="w-3 h-3 rounded-full mt-2 shrink-0 ring-1 ring-inset ring-black/10" style={ "background-color: " + colorOrDefault(data.Color) }></span>
<div class="min-w-0">
<h1 class="text-2xl font-semibold break-words leading-tight">{ data.Form.Summary }</h1>
<p class="text-sm text-gray-500 mt-1">{ data.Form.CalendarLabel }</p>
</div>
</div>
if !data.Form.Writable {
<p class="mb-5 text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded px-3 py-2">
This calendar was shared with you as read-only you can view this event but not change it.
</p>
}
<dl class="space-y-4">
<div>
<dt class="text-xs font-medium uppercase tracking-wide text-gray-400 mb-1">When</dt>
<dd class="text-base text-gray-900">{ eventRangeText(data.Form) }</dd>
</div>
if data.Form.Location != "" {
<div>
<dt class="text-xs font-medium uppercase tracking-wide text-gray-400 mb-1">Location</dt>
<dd class="text-base text-gray-900 break-words">{ data.Form.Location }</dd>
</div>
}
if data.Form.Description != "" {
<div>
<dt class="text-xs font-medium uppercase tracking-wide text-gray-400 mb-1">Description</dt>
<dd class="text-base text-gray-900 whitespace-pre-wrap break-words">{ data.Form.Description }</dd>
</div>
}
</dl>
</div>
}
}
// eventRangeText renders a human-readable "when" string for an event:
// a single timed event reads "Aug 5, 2026, 14:00 15:00"; a multi-day
// range reads "Aug 5 7, 2026"; a single all-day date reads
// "August 5, 2026".
func eventRangeText(f EventFormData) string {
if f.AllDay {
if f.StartDate != f.EndDate {
s, err := dateOnly(f.StartDate)
if err != nil {
return f.StartDate
}
e, err := dateOnly(f.EndDate)
if err != nil {
return f.EndDate
}
if s.Year() == e.Year() && s.Month() == e.Month() {
return fmt.Sprintf("%s %s, %d", s.Format("Jan 2"), e.Format("2"), s.Year())
}
return fmt.Sprintf("%s %s", s.Format("Jan 2, 2006"), e.Format("Jan 2, 2006"))
}
d, err := dateOnly(f.StartDate)
if err != nil {
return f.StartDate
}
return d.Format("January 2, 2006")
}
s, err := dateTime(f.StartDate, f.StartTime)
if err != nil {
return f.StartDate
}
e, err := dateTime(f.EndDate, f.EndTime)
if err != nil {
return s.Format("January 2, 2006, 15:04")
}
if s.Day() == e.Day() {
return fmt.Sprintf("%s, %s %s", s.Format("January 2, 2006"), s.Format("15:04"), e.Format("15:04"))
}
if s.Year() == e.Year() && s.Month() == e.Month() {
return fmt.Sprintf("%s %s, %d", s.Format("Jan 2, 15:04"), e.Format("15:04"), s.Year())
}
return fmt.Sprintf("%s %s", s.Format("Jan 2, 2006, 15:04"), e.Format("Jan 2, 2006, 15:04"))
}
func dateOnly(ds string) (time.Time, error) {
return time.ParseInLocation("2006-01-02", ds, time.Local)
}
func dateTime(ds, ts string) (time.Time, error) {
if ts == "" {
return time.ParseInLocation("2006-01-02", ds, time.Local)
}
return time.ParseInLocation("2006-01-02T15:04", ds+"T"+ts, time.Local)
}
templ EventForm(username string, data EventFormData, errMsg string) { templ EventForm(username string, data EventFormData, errMsg string) {
@Layout("Calendar", username) { @Layout("Calendar", username) {
<a href="/web/calendar" class="text-sm text-indigo-600 hover:underline">&larr; Calendar</a> <a href="/web/calendar" class="text-sm text-indigo-600 hover:underline">&larr; Calendar</a>
File diff suppressed because it is too large Load Diff
+48
View File
@@ -33,6 +33,54 @@ func TestEventTextColorDarkensLightColors(t *testing.T) {
} }
} }
// TestEventRangeText pins the human-readable "When" strings shown on the
// event detail view so any change to date formatting is intentional.
func TestEventRangeText(t *testing.T) {
cases := []struct {
name string
form EventFormData
want string
}{
{
name: "single allday date",
form: EventFormData{AllDay: true, StartDate: "2026-08-05", EndDate: "2026-08-05"},
want: "August 5, 2026",
},
{
name: "all-day multi-day same month",
form: EventFormData{AllDay: true, StartDate: "2026-08-05", EndDate: "2026-08-07"},
want: "Aug 5 7, 2026",
},
{
name: "all-day multi-day different months",
form: EventFormData{AllDay: true, StartDate: "2026-08-30", EndDate: "2026-09-02"},
want: "Aug 30, 2026 Sep 2, 2026",
},
{
name: "timed same day",
form: EventFormData{AllDay: false, StartDate: "2026-08-05", StartTime: "14:00", EndDate: "2026-08-05", EndTime: "15:00"},
want: "August 5, 2026, 14:00 15:00",
},
{
name: "timed different days same month",
form: EventFormData{AllDay: false, StartDate: "2026-08-05", StartTime: "23:30", EndDate: "2026-08-06", EndTime: "01:00"},
want: "Aug 5, 23:30 01:00, 2026",
},
{
name: "timed different months",
form: EventFormData{AllDay: false, StartDate: "2026-08-31", StartTime: "10:00", EndDate: "2026-09-01", EndTime: "11:00"},
want: "Aug 31, 2026, 10:00 Sep 1, 2026, 11:00",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := eventRangeText(c.form); got != c.want {
t.Errorf("eventRangeText(%+v) = %q, want %q", c.form, got, c.want)
}
})
}
}
func TestEventTextColorFallsBackForInvalidInput(t *testing.T) { func TestEventTextColorFallsBackForInvalidInput(t *testing.T) {
if got := eventTextColor(""); got != colorOrDefault("") { if got := eventTextColor(""); got != colorOrDefault("") {
t.Errorf("eventTextColor(\"\") = %s, want the same default colorOrDefault returns", got) t.Errorf("eventTextColor(\"\") = %s, want the same default colorOrDefault returns", got)
+1 -1
View File
File diff suppressed because one or more lines are too long