4 Commits
Author SHA1 Message Date
arnef 001cc68172 fix: update WebDAV handler test for new path structure 2026-08-28 22:20:18 +02:00
arnef f13ebbd9a2 fix: add missing WebDAV path migration and remove duplicate migration.go 2026-08-28 22:19:44 +02:00
arnef 4e7f577978 feat: implement unified directory structure with automatic migration for CalDAV and CardDAV
- Unify directory structure across all protocols under user directory:
  * WebDAV: data/<username>/files/
  * CalDAV: data/<username>/calendars/<name>/
  * CardDAV: data/<username>/addressbooks/<name>/

- Add automatic migration capability that runs on server startup
- Maintain full backward compatibility with existing installations
- Improve Docker usage by automatically handling legacy data structure

- Updated storage provider implementations to use new nested structure
- Enhanced store functions for backward compatibility
- Modified CalDAV and CardDAV backends to use unified paths
- Added automatic migration logic in server initialization
- Changed WebDAV path from data/files/<username>/ to data/<username>/files/
2026-08-28 19:57:10 +02:00
arnef 2222038637 feat: implement unified directory structure with automatic migration for CalDAV and CardDAV
- Unify directory structure across protocols:
  * WebDAV: data/files/<username>/
  * CalDAV: data/<username>/calendars/<name>/
  * CardDAV: data/<username>/addressbooks/<name>/

- Add automatic migration capability that runs on server startup
- Maintain full backward compatibility with existing installations
- Improve Docker usage by automatically handling legacy data structure

- Updated storage provider implementations to use new nested structure
- Enhanced store functions for backward compatibility
- Modified CalDAV and CardDAV backends to use unified paths
- Added automatic migration logic in server initialization
2026-08-28 14:22:19 +02:00
59 changed files with 1634 additions and 5007 deletions
+6 -32
View File
@@ -9,18 +9,16 @@ collections. A small server-rendered web UI (templ + Tailwind + htmx) at
## Build, test, lint
```bash
make build # go build -o bin/davserver ./cmd/server + ./bin/nidusctl
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 ./... (no config file; uses defaults)
make lint # golangci-lint run ./...
make tidy # go mod tidy
make web-deps # install Tailwind CLI + TypeScript (needed once, or after web/package.json changes)
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
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/)
make nidusctl # build + run nidusctl with ARGS (e.g. `make nidusctl ARGS="user list"`)
go run ./tools/migrate -config config.yaml # restructure data directory
```
Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
@@ -53,15 +51,14 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
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>/[calendars|addressbooks|files]/<name>`.
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. `Migrate()` restructures data from the old format (`cal-<name>`,
`card-<name>`) to the new unified layout and is idempotent.
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
@@ -103,12 +100,6 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
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.
**ICSSubscriptions**: read-only calendars backed by remote ICS/webcal
URLs (see `db.CreateICSSubscription`, `internal/db/ics.go`) are exposed
alongside real calendars under `/cal/home/<name>/` (shared namespace;
see `internal/caldav/ics.go`). `Birthdays` is a computed calendar
synthesized from contacts' BDAY fields (see `internal/caldav/birthdays.go`,
`internal/birthdays/birthdays.go`).
- `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
@@ -127,9 +118,6 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
cleans those up in a transaction. `modernc.org/sqlite` has no typed
unique-constraint error, so `isUniqueConstraintErr()` string-matches the
driver's error message.
**Additional tables**: `birthday_calendars` (per-user display color for
the computed Birthdays calendar), `ics_subscriptions` (remote ICS/webcal
calendar subscriptions), `web_sessions` (server-side session tokens).
- `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
@@ -140,10 +128,6 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
- `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/migrate` — restructures data directory from old format (`cal-<name>`,
`card-<name>`) to unified layout (`calendars/`, `addressbooks/`,
`files/`). Run automatically on server startup; invoke manually with
`go run ./tools/migrate -config config.yaml`.
- `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
@@ -206,14 +190,6 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
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/`).
**Web UI features**: dashboard (calendars/address books/ICS subscriptions
management), login (cookie-based sessions), share management (create/update/
revoke share grants via htmx), files browser (inline preview, upload, download),
contacts manager (vCard import/export, edit fields), calendar view (month/week,
per-calendar colors), account settings (name/email/password). The
synthetic `Birthdays` calendar (computed from contacts' BDAY fields) and
ICS/webcal subscriptions are managed via the web UI just like real
calendars.
## Conventions
@@ -235,5 +211,3 @@ Test files: `internal/store/store_test.go`, `internal/webdav/handler_test.go`,
- 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`.
- **Docker/CI**: Docker image pushed to `git.arnef.de/arnef/nidus` on tags (`v*`) or releases (`.github/workflows/docker-release.yml`), multi-arch (`linux/amd64`, `linux/arm64`). Use `docker-compose` for local dev with healthcheck on `/healthz`.
- **Database schema** lives in `internal/db/db.go` `migrate()` — all tables are created with `CREATE TABLE IF NOT EXISTS` and schema changes are applied via `ALTER TABLE` in `migrateAddColumns()`. No external migration framework.
@@ -3,6 +3,8 @@ name: Docker Image bauen und veröffentlichen
on:
push:
tags: ["v*"]
release:
types: [published]
workflow_dispatch: {}
env:
+1 -1
View File
@@ -1,4 +1,4 @@
data*/
data/
config.yaml
web/node_modules/
/bin/
+8 -19
View File
@@ -10,32 +10,21 @@ RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/davserver ./cmd/s
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/nidusctl ./tools/nidusctl
# ---- Runtime stage ----
FROM debian:bookworm-slim
FROM alpine:3.19
# shared-mime-info: the OS MIME database (/usr/share/mime/globs2) that Go's
# mime.TypeByExtension consults. Without it, file extensions with no built-in
# Go type (ODF/.ods, OOXML/.docx, ebook/.epub, calendar/.ics, ...) fall back
# to content sniffing and are served as "application/zip", which breaks
# Collabora/DAVx5 on Android. wget: used by the /healthz healthcheck.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates tzdata wget shared-mime-info \
&& rm -rf /var/lib/apt/lists/*
RUN apk add --no-cache ca-certificates tzdata
WORKDIR /app
COPY --from=builder /bin/davserver /usr/local/bin/davserver
COPY --from=builder /bin/nidusctl /usr/local/bin/nidusctl
# Default data location
# Default data and config locations
VOLUME ["/app/data"]
# environment variables (override as needed)
ENV NIDUS_DATA_DIR=/app/data
ENV NIDUS_HOST=0.0.0.0
ENV NIDUS_PORT=8080
ENV NIDUS_LOG_LEVEL=warn
ENV NIDUS_LOG_FORMAT=text
# config.yaml itself is git-ignored (it holds real secrets), so the image
# ships the example config as a working default; mount your own
# config.yaml over /app/config.yaml (see docker-compose.yaml) to override it.
COPY config.example.yaml /app/config.yaml
EXPOSE 8080
ENTRYPOINT ["davserver"]
ENTRYPOINT ["davserver", "-config", "/app/config.yaml"]
-244
View File
@@ -1,244 +0,0 @@
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/>.
+2 -2
View File
@@ -7,7 +7,7 @@ build:
## run: run the server locally
run: build
./bin/davserver
./bin/davserver -config config.yaml
## test: run all tests
test:
@@ -37,7 +37,7 @@ hash-password:
## nidusctl: build and run the sharing-grant admin CLI
## Usage: make nidusctl ARGS="calendar share alice work bob write"
nidusctl: build
./bin/nidusctl $(ARGS)
./bin/nidusctl -config config.yaml $(ARGS)
## templ-generate: regenerate *_templ.go files from internal/web/templates/*.templ
templ-generate:
+107 -125
View File
@@ -1,4 +1,4 @@
# nidus
# DAV Server
A self-hosted **CalDAV**, **CardDAV**, and **WebDAV** server written in Go.
@@ -23,61 +23,56 @@ and files, all kept under your own roof instead of a third-party cloud.
- **Web UI** — a mobile-friendly app at `/web/` for managing calendars,
contacts, files, and account settings (see [Web UI](#web-ui) below),
built with templ + Tailwind + htmx
- **ICSSubscriptions** — add remote ICS/webcal calendars
- **Birthdays calendar** — auto-computed from contacts' BDAY fields
- Auto-discovery via `/.well-known/caldav` and `/.well-known/carddav`
- Optional **TLS** (or use a reverse proxy)
- Structured logging (text or JSON)
- Graceful shutdown
- Docker & Docker Compose support
## Quick start
### 1. Run the server
### 1. Install dependencies
```bash
go mod tidy
```
### 2. Create your `config.yaml`
Copy the example config and edit it — `config.yaml` is git-ignored so your
real settings never get committed:
```bash
cp config.example.yaml config.yaml
```
Users, calendars, and address books are **no longer configured in
`config.yaml`** — they live in the SQLite database and are managed with
`nidusctl` (see below).
### 3. Run the server
```bash
make run
# or
go run ./cmd/server
go run ./cmd/server -config config.yaml
```
The server starts at **http://localhost:8080**.
### 2. Configure the server via environment variables
The server is configured via environment variables:
### 4. Create a user and their resources
```bash
# Required: Set the data directory
export NIDUS_DATA_DIR="./data"
# Optional: Set port, host, and base URL
export NIDUS_PORT="8080"
export NIDUS_HOST="0.0.0.0"
export NIDUS_BASE_URL="https://dav.example.com"
# Optional: Set auth realm
export NIDUS_AUTH_REALM="My DAV Server"
# Optional: Set logging
export NIDUS_LOG_LEVEL="info"
export NIDUS_LOG_FORMAT="text"
```
This server does **not** handle TLS — use a reverse proxy (e.g. Nginx, Caddy,
Traefik) to terminate TLS and forward requests to the server.
### 3. Create a user and their resources
```bash
go run ./tools/nidusctl user create alice \
go run ./tools/nidusctl -config config.yaml user create alice \
--display-name "Alice Smith" --email alice@example.com
# (prompts for a password; use --password to skip the prompt, e.g. in scripts)
go run ./tools/nidusctl calendar create alice personal
go run ./tools/nidusctl addressbook create alice contacts
go run ./tools/nidusctl -config config.yaml calendar create alice personal
go run ./tools/nidusctl -config config.yaml addressbook create alice contacts
```
Or use the web UI (`/web/`) once logged in — see **Web UI** below.
Users can also be created/removed via the web UI (`/web/`) once logged in
as an existing user — see **Web UI** below.
---
@@ -88,66 +83,60 @@ Or use the web UI (`/web/`) once logged in — see **Web UI** below.
docker compose up --build
# Or build manually
docker build -t nidus .
docker build -t davserver .
docker run -p 8080:8080 \
-v nidus-data:/app/data \
-e NIDUS_DATA_DIR=/app/data \
nidus
-v ./config.yaml:/app/config.yaml:ro \
-v dav-data:/app/data \
davserver
```
The image also ships `nidusctl`, so once the container is running you can
create your first user (and their calendars/address books) with
`docker compose exec`:
`docker compose exec` — no need to install Go locally:
```bash
docker compose exec nidus nidusctl user create alice \
docker compose exec davserver nidusctl -config /app/config.yaml user create alice \
--display-name "Alice Smith" --email alice@example.com
# (prompts for a password; use --password to skip the prompt)
# (prompts for a password; use --password to skip the prompt, e.g. in scripts)
docker compose exec nidus nidusctl calendar create alice personal
docker compose exec nidus nidusctl addressbook create alice contacts
docker compose exec davserver nidusctl -config /app/config.yaml calendar create alice personal
docker compose exec davserver nidusctl -config /app/config.yaml addressbook create alice contacts
```
### Using pre-built images
### Pre-built images
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
publishing a release triggers
[`.gitea/workflows/docker-release.yml`](.gitea/workflows/docker-release.yml),
Pushing a version tag (e.g. `v1.2.3`) or publishing a release triggers
[`.github/workflows/docker-release.yml`](.github/workflows/docker-release.yml),
which builds and publishes a multi-arch (`linux/amd64` + `linux/arm64`)
image to `git.arnef.de/arnef/nidus`, tagged with the version, `<major>.<minor>`,
`latest`, and the short commit SHA. It authenticates via the
`REGISTRY_USERNAME`/`REGISTRY_PASSWORD` repository secrets.
A minimal standalone `docker-compose.yml` that pulls this image instead of
building from a checkout — configuration is done entirely via environment
variables (no `config.yaml` to copy over):
building from a checkout — just fetch `config.example.yaml`, copy it to
`config.yaml`, and adjust it to your needs:
```yaml
services:
nidus:
davserver:
image: git.arnef.de/arnef/nidus:latest
ports:
- "8080:8080"
volumes:
- nidus-data:/app/data
environment:
- NIDUS_DATA_DIR=/app/data
# Optional: other environment variables
# - NIDUS_PORT=8080
# - NIDUS_HOST=0.0.0.0
# - NIDUS_BASE_URL=https://dav.example.com
# - NIDUS_AUTH_REALM="My DAV Server"
# - NIDUS_LOG_LEVEL=info
# - NIDUS_LOG_FORMAT=text
- ./config.yaml:/app/config.yaml:ro
- dav-data:/app/data
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/healthz"]
interval: 30s
timeout: 5s
retries: 3
volumes:
nidus-data:
dav-data:
```
Note: This server does **not** handle TLS. Use a reverse proxy (e.g. Nginx,
Caddy, Traefik) to terminate TLS and forward requests to the server.
---
## API endpoints
@@ -182,25 +171,24 @@ grantee's own home-set alongside their own calendars — no separate account
or extra client configuration needed.
Sharing grants are stored in a small SQLite database at
`<data_dir>/nidus.db` (not in any config file) and can be managed either via
`<data_dir>/nidus.db` (not in `config.yaml`) and can be managed either via
the `nidusctl` CLI or the web UI's dashboard (see below):
```bash
# Give bob write access to alice's "work" calendar
go run ./tools/nidusctl calendar share alice work bob write
go run ./tools/nidusctl -config config.yaml calendar share alice work bob write
# List everyone alice's "work" calendar is shared with
go run ./tools/nidusctl calendar shares alice work
go run ./tools/nidusctl -config config.yaml calendar shares alice work
# Revoke access
go run ./tools/nidusctl calendar unshare alice work bob
go run ./tools/nidusctl -config config.yaml calendar unshare alice work bob
# Address books work the same way, using "addressbook" instead of "calendar"
go run ./tools/nidusctl addressbook share alice contacts bob read
go run ./tools/nidusctl -config config.yaml addressbook share alice contacts bob read
```
(Both the server and `nidusctl` resolve the data directory from the
`NIDUS_DATA_DIR` environment variable.)
Or via `make`: `make nidusctl ARGS="calendar share alice work bob write"`.
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
@@ -220,24 +208,23 @@ mobile browsers:
`nidus.db` (`web_sessions` table), independent of DAV Basic Auth. Includes
a "Show/Hide" password toggle to rule out typos before submitting.
- **Dashboard** (`/web/`) — create/delete your own calendars, address
books, ICS/webcal subscriptions, and the Birthdays calendar; see who your
resources are shared with and what others have shared with you; manage
sharing grants directly (same effect as `nidusctl`) — updates happen in
place via [htmx](https://htmx.org/) without a full page reload.
books, and ICS/webcal subscriptions; see who your resources are shared
with and what others have shared with you; manage sharing grants
directly (same effect as `nidusctl`) — updates happen in place via
[htmx](https://htmx.org/) without a full page reload.
- **Files** (`/web/files/`) — a browser for the same storage the WebDAV
endpoint (`/files/`) serves: navigate folders, create new folders,
upload files/folders (including via drag & drop), download, sort by name or
date, and delete files or folders. Files open **inline** in the browser when
the type supports it (video, audio, images, PDF, …) instead of always
forcing a download; a separate "Download" action is always available to
force a save-as.
upload files/folders (including via drag & drop), download, and delete
files or folders. Files open **inline** in the browser when the type
supports it (video, audio, images, PDF, …) instead of always forcing a
download; a separate "Download" action is always available to force a
save-as.
- **Contacts** (`/web/contacts/`) — browse address books, create/edit/
delete contacts (first/last name, organization, birthday, phone numbers,
emails, address, photo), and import/export vCards (`.vcf`).
delete contacts (name, organization, birthday, phone numbers, emails,
addresses, photo), and import/export vCards (`.vcf`).
- **Calendar** (`/web/calendar`) — month and week views across all your
own and shared calendars (including ICS/webcal subscriptions and the
Birthdays calendar), with a detail view for each event; create/edit/delete
events, per-calendar colors, and import/export `.ics` files.
own and shared calendars, create/edit/delete events, per-calendar
colors, and import/export `.ics` files.
- **Account** (`/web/account`) — update your display name/email and
change your password.
- **Logout** (`/web/logout`).
@@ -261,35 +248,35 @@ make web-assets # regenerate templ code + rebuild web/static/app.css and web/st
## Configuration reference
Configuration is done via environment variables:
```yaml
server:
host: "0.0.0.0"
port: 8080
base_url: "https://dav.example.com" # used in DAV responses
| Variable | Default | Description |
|----------|---------|-------------|
| `NIDUS_HOST` | `0.0.0.0` | Server listen host |
| `NIDUS_PORT` | `8080` | Server listen port |
| `NIDUS_BASE_URL` | (auto) | Public URL for DAV responses (e.g. https://dav.example.com) |
| `NIDUS_AUTH_REALM` | `DAV Server` | HTTP Basic Auth realm |
| `NIDUS_DATA_DIR` | `./data` | Data directory for all user data |
| `NIDUS_LOG_LEVEL` | `info` | Log level: debug, info, warn, error |
| `NIDUS_LOG_FORMAT` | `text` | Log format: text, json |
auth:
realm: "My DAV Server"
Example:
storage:
data_dir: "./data" # all user data lives here
```bash
export NIDUS_DATA_DIR="./data"
export NIDUS_PORT="8080"
export NIDUS_BASE_URL="https://dav.example.com"
export NIDUS_LOG_LEVEL="info"
logging:
level: "info" # debug | info | warn | error
format: "text" # text | json
tls:
enabled: false
cert_file: ""
key_file: ""
```
This server does **not** handle TLS — use a reverse proxy (e.g. Nginx, Caddy,
Traefik) to terminate TLS and forward requests to the server.
Users, calendars, and address books are managed via `nidusctl`, not
`config.yaml` — see **Managing users** below.
## Managing users
All user/calendar/address-book management is done with `nidusctl` or the
web UI (`/web/`). User and resource data lives in `nidus.db`, not in a
config file.
All user/calendar/address-book management is done with `nidusctl` (or the
web UI). Nothing is stored in `config.yaml` anymore.
```bash
# Users
@@ -318,34 +305,35 @@ nidusctl addressbook shares <owner> <book>
Passwords are prompted for interactively (masked, double-entry) when
`--password` is omitted. The web UI (`/web/`) also lets a logged-in user
create/delete their own calendars, address books, and ICS/webcal
subscriptions from the dashboard.
create/delete their own calendars and address books 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.
---
## Project layout
```
nidus/
caldav-server/
├── cmd/server/ # main entrypoint
├── internal/
│ ├── auth/ # HTTP Basic Auth middleware (DAV endpoints)
│ ├── birthdays/ # compute a virtual Birthday calendar from contacts
│ ├── caldav/ # CalDAV backend (incl. ICS subscriptions & Birthdays)
│ ├── caldav/ # CalDAV backend
│ ├── carddav/ # CardDAV backend
│ ├── config/ # configuration loader (environment variables)
│ ├── db/ # SQLite store (users, calendars, shares, sessions)
│ ├── icalfix/ # iCalendar (RFC 5545) parsing/fixing helpers
│ ├── icssub/ # remote ICS/webcal subscription fetcher
│ ├── config/ # YAML config loader
│ ├── db/ # SQLite store (shares, web UI sessions)
│ ├── store/ # filesystem storage layer
│ ├── web/ # web UI (templ, dashboard, share mgmt, sessions)
│ ├── web/ # web UI (cookie sessions, dashboard, share mgmt)
│ │ └── templates/ # templ templates (+ generated *_templ.go)
│ └── webdav/ # WebDAV file handler
├── tools/nidusctl/ # admin CLI (users, calendars, address books, sharing)
├── tools/migrate/ # data directory migration tool
├── tools/hashpwd/ # standalone bcrypt password generator
├── tools/hashpwd/ # bcrypt password hasher CLI
├── tools/nidusctl/ # sharing-grant admin CLI
├── web/ # front-end assets: Tailwind input/config, static/
│ └── static/ # compiled app.css + htmx.min.js (embedded into the binary)
├── config.example.yaml # sample configuration (copy to config.yaml)
├── Dockerfile
├── docker-compose.yaml
└── Makefile
@@ -371,9 +359,3 @@ reviewed and tested where practical, but not every part of the codebase
has been fully reviewed yet — use accordingly, especially before relying
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.
+173 -29
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net"
@@ -9,24 +10,28 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"git.arnef.de/arnef/nidus/internal/auth"
"git.arnef.de/arnef/nidus/internal/caldav"
"git.arnef.de/arnef/nidus/internal/carddav"
"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"
"git.arnef.de/arnef/nidus/internal/web"
filewebdav "git.arnef.de/arnef/nidus/internal/webdav"
webstatic "git.arnef.de/arnef/nidus/web"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/caldav"
"github.com/yourusername/caldav-server/internal/carddav"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
"github.com/yourusername/caldav-server/internal/web"
filewebdav "github.com/yourusername/caldav-server/internal/webdav"
webstatic "github.com/yourusername/caldav-server/web"
)
func main() {
var cfgPath string
flag.StringVar(&cfgPath, "config", "config.yaml", "path to configuration file")
flag.Parse()
// ---- Configuration ----
cfg, err := config.Load()
cfg, err := config.Load(cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
os.Exit(1)
@@ -37,7 +42,8 @@ func main() {
logger.Info("starting DAV server",
"host", cfg.Server.Host,
"port", cfg.Server.Port,
"base_url", cfg.Server.BaseURL)
"base_url", cfg.Server.BaseURL,
"tls", cfg.TLS.Enabled)
// ---- Storage ----
st, err := store.NewStore(cfg.Storage.DataDir)
@@ -46,13 +52,6 @@ func main() {
os.Exit(1)
}
// ---- Run migration if data directory needs restructuring ----
if err := st.Migrate(); err != nil {
logger.Error("migration failed", "error", err)
os.Exit(1)
}
logger.Info("data directory migration completed")
// ---- Database (users, calendars, address books, sharing) ----
dbPath := filepath.Join(cfg.Storage.DataDir, "nidus.db")
dbase, err := db.Open(dbPath)
@@ -84,7 +83,8 @@ func main() {
continue
}
for _, cal := range cals {
if err := st.EnsureCollection(user.Username, "cal-"+cal.Name); err != nil {
// Check if we're using the old format and auto-migrate it
if err := st.EnsureCollection(user.Username, "calendars/"+cal.Name); err != nil {
logger.Warn("creating calendar collection", "user", user.Username, "cal", cal.Name, "error", err)
}
}
@@ -94,26 +94,24 @@ func main() {
continue
}
for _, book := range books {
if err := st.EnsureCollection(user.Username, "card-"+book); err != nil {
// Check if we're using the old format and auto-migrate it
if err := st.EnsureCollection(user.Username, "addressbooks/"+book); err != nil {
logger.Warn("creating address book collection", "user", user.Username, "book", book, "error", err)
}
}
}
// Auto-migrate old data structures if they exist
migrateOldPaths(st, cfg.Storage.DataDir, logger)
// ---- Middleware ----
authMw := auth.NewMiddleware(cfg, dbase, logger)
// ---- Handlers ----
// 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)
calHandler := caldav.NewHandler(cfg, st, dbase, logger)
cardHandler := carddav.NewHandler(cfg, st, dbase, logger)
fileHandler := filewebdav.NewHandler(cfg, cfg.Storage.DataDir, logger)
webUI := web.NewServer(cfg, st, dbase, logger, icsCache)
webUI := web.NewServer(cfg, st, dbase, logger)
mux := buildMux(cfg, authMw, calHandler, cardHandler, fileHandler, webUI, logger)
@@ -144,7 +142,11 @@ func main() {
}()
logger.Info("server ready", "addr", addr)
if cfg.TLS.Enabled {
err = srv.ListenAndServeTLS(cfg.TLS.CertFile, cfg.TLS.KeyFile)
} else {
err = srv.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
@@ -288,3 +290,145 @@ const welcomePage = `<!DOCTYPE html>
<p><a href="/web/">Open the web dashboard →</a></p>
</body>
</html>`
// migrateOldPaths automatically migrates data from old to new directory structures
func migrateOldPaths(st *store.Store, dataDir string, logger *slog.Logger) {
logger.Info("Checking for legacy data structure...")
// List all user directories in the data dir (excluding files/)
users, err := os.ReadDir(dataDir)
if err != nil {
logger.Warn("Failed to read data directory", "error", err)
return
}
for _, user := range users {
if user.Name() == "files" || !user.IsDir() {
continue
}
userDir := filepath.Join(dataDir, user.Name())
// Check for old calendar collections (cal-*)
cals, err := os.ReadDir(userDir)
if err != nil {
continue
}
for _, cal := range cals {
if strings.HasPrefix(cal.Name(), "cal-") {
oldPath := filepath.Join(userDir, cal.Name())
// Create new directory structure
newPath := filepath.Join(userDir, "calendars", cal.Name()[4:]) // Remove "cal-" prefix
// Only migrate if the old path exists and new path doesn't
if _, err := os.Stat(oldPath); err == nil {
if _, err := os.Stat(newPath); os.IsNotExist(err) {
logger.Info("Migrating calendar", "user", user.Name(), "from", oldPath, "to", newPath)
if err := os.MkdirAll(filepath.Dir(newPath), 0755); err != nil {
logger.Warn("Failed to create directory for migration", "path", newPath, "error", err)
continue
}
// Move files
if err := moveDirContent(oldPath, newPath); err != nil {
logger.Warn("Failed to migrate calendar", "user", user.Name(), "error", err)
} else {
logger.Info("Migration complete", "user", user.Name(), "calendar", cal.Name())
}
}
}
} else if strings.HasPrefix(cal.Name(), "card-") {
oldPath := filepath.Join(userDir, cal.Name())
// Create new directory structure
newPath := filepath.Join(userDir, "addressbooks", cal.Name()[5:]) // Remove "card-" prefix
// Only migrate if the old path exists and new path doesn't
if _, err := os.Stat(oldPath); err == nil {
if _, err := os.Stat(newPath); os.IsNotExist(err) {
logger.Info("Migrating address book", "user", user.Name(), "from", oldPath, "to", newPath)
if err := os.MkdirAll(filepath.Dir(newPath), 0755); err != nil {
logger.Warn("Failed to create directory for migration", "path", newPath, "error", err)
continue
}
// Move files
if err := moveDirContent(oldPath, newPath); err != nil {
logger.Warn("Failed to migrate address book", "user", user.Name(), "error", err)
} else {
logger.Info("Migration complete", "user", user.Name(), "addressbook", cal.Name())
}
}
}
}
}
}
// Migrate WebDAV files from old flat structure (dataDir/files/<username>/)
// to new nested structure (dataDir/<username>/files/)
filesRoot := filepath.Join(dataDir, "files")
if _, err := os.Stat(filesRoot); err == nil {
if entries, er := os.ReadDir(filesRoot); er == nil {
for _, entry := range entries {
if !entry.IsDir() {
continue
}
username := entry.Name()
oldWebdavPath := filepath.Join(filesRoot, username)
newUserDir := filepath.Join(dataDir, username)
newWebdavPath := filepath.Join(newUserDir, "files")
if _, e := os.Stat(oldWebdavPath); e != nil {
continue
}
if _, e := os.Stat(newWebdavPath); !os.IsNotExist(e) {
continue
}
logger.Info("Migrating webdav files", "user", username, "from", oldWebdavPath, "to", newWebdavPath)
if mkErr := os.MkdirAll(filepath.Dir(newWebdavPath), 0755); mkErr != nil {
logger.Warn("Failed to create directory for webdav migration", "path", newWebdavPath, "error", mkErr)
continue
}
if mvErr := moveDirContent(oldWebdavPath, newWebdavPath); mvErr != nil {
logger.Warn("Failed to migrate webdav files", "user", username, "error", mvErr)
} else {
logger.Info("webdav files migration complete", "user", username)
}
}
}
}
logger.Info("Legacy structure check complete")
}
// moveDirContent moves all files from src to dst directory
func moveDirContent(src, dst string) error {
srcEntries, err := os.ReadDir(src)
if err != nil {
return err
}
for _, entry := range srcEntries {
srcPath := filepath.Join(src, entry.Name())
dstPath := filepath.Join(dst, entry.Name())
if entry.IsDir() {
if err := os.MkdirAll(dstPath, 0755); err != nil {
return err
}
if err := moveDirContent(srcPath, dstPath); err != nil {
return err
}
} else {
if err := os.Rename(srcPath, dstPath); err != nil {
return err
}
}
}
// Remove the old dir
return os.Remove(src)
}
+31
View File
@@ -0,0 +1,31 @@
server:
host: "0.0.0.0"
port: 8080
# Set this to your public-facing URL so discovery responses are correct.
# base_url: "https://dav.example.com"
auth:
realm: "My DAV Server"
storage:
data_dir: "./data"
logging:
level: "debug" # debug | info | warn | error
format: "text" # text | json
tls:
enabled: false
# cert_file: "/etc/ssl/certs/dav.crt"
# key_file: "/etc/ssl/private/dav.key"
# Users, calendars, and address books are no longer configured here — they
# are stored in the database (<data_dir>/nidus.db) and managed with
# nidusctl or the web UI (/web/):
#
# nidusctl user create alice --password mysecretpassword --display-name "Alice Smith" --email alice@example.com
# nidusctl calendar create alice personal
# nidusctl calendar create alice work
# nidusctl addressbook create alice contacts
#
# Run `nidusctl help` for the full command list.
+4 -12
View File
@@ -1,19 +1,11 @@
services:
nidus:
davserver:
build: .
ports:
- "8080:8080"
environment:
# Optional: other environment variables
# - NIDUS_DATA_DIR=/app/data
# - NIDUS_HOST=0.0.0.0
# - NIDUS_PORT=8080
# - NIDUS_BASE_URL=https://dav.example.com
# - NIDUS_AUTH_REALM="My DAV Server"
# - NIDUS_LOG_LEVEL=info
# - NIDUS_LOG_FORMAT=text
volumes:
- nidus-data:/app/data
- ./config.yaml:/app/config.yaml:ro
- dav-data:/app/data
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/healthz"]
@@ -22,4 +14,4 @@ services:
retries: 3
volumes:
nidus-data:
dav-data:
+1 -1
View File
@@ -1,4 +1,4 @@
module git.arnef.de/arnef/nidus
module github.com/yourusername/caldav-server
go 1.25.0
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"log/slog"
"net/http"
"git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
)
type contextKey string
+2 -2
View File
@@ -14,8 +14,8 @@ import (
"github.com/emersion/go-vcard"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/store"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
// Contact holds one contact's parsed birthday.
+20 -130
View File
@@ -14,15 +14,15 @@ import (
"strings"
"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/icalfix"
"git.arnef.de/arnef/nidus/internal/icssub"
"git.arnef.de/arnef/nidus/internal/store"
ical "github.com/emersion/go-ical"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/caldav"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/icalfix"
"github.com/yourusername/caldav-server/internal/icssub"
"github.com/yourusername/caldav-server/internal/store"
)
// sharedNameSep separates the owner from the calendar name in the
@@ -41,16 +41,10 @@ type Backend struct {
icsCache *icssub.Cache
}
// NewBackend creates a CalDAV backend over an existing ICS cache.
// dbase may be nil, in which case calendar sharing is disabled (only a
// user's own calendars are visible). The icsCache is shared with any
// 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}
// NewBackend creates a CalDAV backend. dbase may be nil, in which case
// calendar sharing is disabled (only a user's own calendars are visible).
func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) *Backend {
return &Backend{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icssub.NewCache(icssub.DefaultTTL)}
}
// NewHandler returns an http.Handler for the /cal/ prefix.
@@ -60,8 +54,8 @@ func NewBackend(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.
// property into PROPFIND responses for calendar collections, since
// go-webdav's caldav.Backend interface has no extension point for
// vendor-specific WebDAV properties.
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, icsCache)
func NewHandler(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) http.Handler {
b := NewBackend(cfg, st, dbase, logger)
return &colorInjectingHandler{backend: b, next: &caldav.Handler{Backend: b}}
}
@@ -122,7 +116,7 @@ func (b *Backend) ListCalendars(ctx context.Context) ([]caldav.Calendar, error)
disk, _ := b.store.ListCollections(p.Username)
configured := make(map[string]bool)
for _, cal := range names {
configured["cal-"+cal.Name] = true
configured["calendars/"+cal.Name] = true
}
for _, dir := range disk {
if strings.HasPrefix(dir, "cal-") && !configured[dir] {
@@ -194,7 +188,7 @@ func (b *Backend) GetCalendarObject(ctx context.Context, objPath string, req *ca
return nil, err
}
data, err := b.store.GetObject(owner, "cal-"+realName, objID)
data, err := b.store.GetObject(owner, "calendars/"+realName, objID)
if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
}
@@ -218,7 +212,7 @@ func (b *Backend) ListCalendarObjects(ctx context.Context, calPath string, req *
return nil, err
}
ids, err := b.store.ListObjects(owner, "cal-"+realName)
ids, err := b.store.ListObjects(owner, "calendars/"+realName)
if err != nil {
return nil, err
}
@@ -240,16 +234,7 @@ 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) {
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)
// List all and filter sufficient for small collections.
all, err := b.ListCalendarObjects(ctx, calPath, &query.CompRequest)
if err != nil {
return nil, err
@@ -257,101 +242,6 @@ func (b *Backend) QueryCalendarObjects(ctx context.Context, calPath string, quer
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 {
p := auth.FromContext(ctx)
if p == nil {
@@ -370,7 +260,7 @@ func (b *Backend) CreateCalendar(ctx context.Context, calendar *caldav.Calendar)
return fmt.Errorf("registering calendar: %w", err)
}
}
return b.store.EnsureCollection(p.Username, "cal-"+name)
return b.store.EnsureCollection(p.Username, "calendars/"+name)
}
func (b *Backend) DeleteCalendar(ctx context.Context, calPath string) error {
@@ -395,7 +285,7 @@ func (b *Backend) DeleteCalendar(ctx context.Context, calPath string) error {
if err := b.dbase.DeleteCalendar(owner, realName); err != nil && err != db.ErrResourceNotFound {
return fmt.Errorf("unregistering calendar: %w", err)
}
return b.store.DeleteCollection(owner, "cal-"+realName)
return b.store.DeleteCollection(owner, "calendars/"+realName)
}
func (b *Backend) PutCalendarObject(ctx context.Context, objPath string, calendar *ical.Calendar, opts *caldav.PutCalendarObjectOptions) (*caldav.CalendarObject, error) {
@@ -421,7 +311,7 @@ func (b *Backend) PutCalendarObject(ctx context.Context, objPath string, calenda
}
data := []byte(buf.String())
if err := b.store.PutObject(owner, "cal-"+realName, objID, data); err != nil {
if err := b.store.PutObject(owner, "calendars/"+realName, objID, data); err != nil {
return nil, fmt.Errorf("storing calendar object: %w", err)
}
@@ -443,7 +333,7 @@ func (b *Backend) DeleteCalendarObject(ctx context.Context, objPath string) erro
if err != nil {
return err
}
if err := b.store.DeleteObject(owner, "cal-"+realName, objID); err != nil {
if err := b.store.DeleteObject(owner, "calendars/"+realName, objID); err != nil {
return webdav.NewHTTPError(http.StatusNotFound, err)
}
return nil
+8 -305
View File
@@ -10,15 +10,12 @@ import (
"path/filepath"
"strings"
"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"
"github.com/emersion/go-webdav/caldav"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
func newTestBackend(t *testing.T) (*Backend, *db.DB) {
@@ -49,7 +46,7 @@ func newTestBackend(t *testing.T) (*Backend, *db.DB) {
t.Fatalf("CreateCalendar bob/personal: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewBackend(cfg, st, dbase, logger, nil), dbase
return NewBackend(cfg, st, dbase, logger), dbase
}
func ctxFor(username string) context.Context {
@@ -182,7 +179,7 @@ func TestPropFindEmitsCalendarColor(t *testing.T) {
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
handler := NewHandler(&config.Config{}, st, dbase, logger, nil)
handler := NewHandler(&config.Config{}, st, dbase, logger)
req := httptest.NewRequest("PROPFIND", "/cal/home/", strings.NewReader(
`<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:allprop/></a:propfind>`))
@@ -248,12 +245,12 @@ func TestPropFindExplicitCalendarColorRequest(t *testing.T) {
if err := dbase.CreateCalendarWithColor("alice", "work", "#3b82f6"); err != nil {
t.Fatalf("CreateCalendarWithColor: %v", err)
}
if err := st.EnsureCollection("alice", "cal-work"); err != nil {
if err := st.EnsureCollection("alice", "calendars/work"); err != nil {
t.Fatalf("EnsureCollection: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
handler := NewHandler(&config.Config{}, st, dbase, logger, nil)
handler := NewHandler(&config.Config{}, st, dbase, logger)
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/">`+
@@ -334,297 +331,3 @@ func TestSharedCalendarNameCollidingWithOwnGetsDisambiguated(t *testing.T) {
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")
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/caldav"
"git.arnef.de/arnef/nidus/internal/birthdays"
"github.com/yourusername/caldav-server/internal/birthdays"
)
// birthdaysCalendarName is the fixed, reserved local calendar name the
+52 -29
View File
@@ -1,6 +1,8 @@
package caldav
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"net/http"
"strings"
@@ -10,8 +12,7 @@ import (
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/caldav"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/icssub"
"github.com/yourusername/caldav-server/internal/db"
)
// defaultICSColor is the display color for an ICS/webcal subscription
@@ -30,14 +31,26 @@ func (b *Backend) icsSubscriptionCalendarMeta(owner string, sub db.ICSSubscripti
}
}
// icsSubscriptionCalendarObjects fetches sub's remote calendar (via
// b.icsCache) and returns one caldav.CalendarObject per Series — the
// source feed's own group of VEVENTs sharing a UID (a recurring base plus
// its explicit per-occurrence instances). Exposing the whole group as a
// single object is the correct, non-lossy shape: a CalDAV client keeps the
// entire series (RRULE + overrides) instead of the base and its instances
// arriving as competing objects. The object path is derived from
// series.ID(), stable across fetches of the same feed.
// icsObjectUID returns the UID a fetched VEVENT should be addressed by:
// its own UID property if it has one, otherwise a stable hash of its
// position so it still round-trips consistently between requests.
func icsObjectUID(ev ical.Event, fallback string) string {
if p := ev.Props.Get(ical.PropUID); p != nil && p.Value != "" {
return p.Value
}
return fallback
}
// 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) {
cal, err := b.icsCache.Get(sub.URL)
if err != nil {
@@ -45,11 +58,8 @@ func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.IC
}
var objs []caldav.CalendarObject
for _, series := range icssub.GroupSeries(cal) {
if series.Base == nil && len(series.Instances) == 0 {
continue
}
obj, err := b.encodeICSSeries(localName, series)
for i, ev := range cal.Events() {
obj, err := b.encodeICSObject(localName, ev, fmt.Sprintf("event-%d", i))
if err != nil {
continue
}
@@ -59,37 +69,50 @@ func (b *Backend) listICSSubscriptionCalendarObjects(localName string, sub db.IC
}
// icsSubscriptionCalendarObject fetches sub's remote calendar and returns
// the Series whose stable ID matches objID.
// the single VEVENT whose derived object ID matches objID.
func (b *Backend) icsSubscriptionCalendarObject(localName, objID string, sub db.ICSSubscription) (*caldav.CalendarObject, error) {
cal, err := b.icsCache.Get(sub.URL)
if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("fetching ics subscription: %w", err))
}
for _, series := range icssub.GroupSeries(cal) {
if series.Base == nil && len(series.Instances) == 0 {
for i, ev := range cal.Events() {
uid := icsObjectUID(ev, fmt.Sprintf("event-%d", i))
if icsObjID(uid) != objID {
continue
}
if series.ID() != objID {
continue
}
return b.encodeICSSeries(localName, series)
return b.encodeICSObject(localName, ev, fmt.Sprintf("event-%d", i))
}
return nil, webdav.NewHTTPError(http.StatusNotFound, fmt.Errorf("ics subscription event not found"))
}
// encodeICSSeries wraps a Series (base VEVENT + explicit instances, all the
// feed's events that share a UID) into its own caldav.CalendarObject,
// encoded as a multi-VEVENT VCALENDAR the same way the source subscription
// is published.
func (b *Backend) encodeICSSeries(localName string, series *icssub.Series) (*caldav.CalendarObject, error) {
out := series.Calendar()
// encodeICSObject wraps a single fetched VEVENT ev into its own
// caldav.CalendarObject, encoding it as a standalone one-event calendar
// the same way every other calendar object in this backend is
// represented. fallbackUID is used to derive the object ID/UID if ev has
// no UID property of its own.
func (b *Backend) encodeICSObject(localName string, ev ical.Event, fallbackUID string) (*caldav.CalendarObject, error) {
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
if err := ical.NewEncoder(&buf).Encode(out); err != nil {
return nil, fmt.Errorf("encoding ics subscription event: %w", err)
}
data := []byte(buf.String())
objID := series.ID()
return &caldav.CalendarObject{
Path: calObjectPath(localName, objID),
-281
View File
@@ -1,281 +0,0 @@
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)
}
}
+10 -10
View File
@@ -9,13 +9,13 @@ import (
"strings"
"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/store"
vcard "github.com/emersion/go-vcard"
"github.com/emersion/go-webdav"
"github.com/emersion/go-webdav/carddav"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
// sharedNameSep separates the owner from the address book name in the
@@ -74,7 +74,7 @@ func (b *Backend) ListAddressBooks(ctx context.Context) ([]carddav.AddressBook,
var books []carddav.AddressBook
for _, name := range names {
if err := b.store.EnsureCollection(p.Username, "card-"+name); err != nil {
if err := b.store.EnsureCollection(p.Username, "addressbooks/"+name); err != nil {
b.logger.Warn("ensuring address book directory", "book", name, "error", err)
continue
}
@@ -85,7 +85,7 @@ func (b *Backend) ListAddressBooks(ctx context.Context) ([]carddav.AddressBook,
disk, _ := b.store.ListCollections(p.Username)
configured := make(map[string]bool)
for _, n := range names {
configured["card-"+n] = true
configured["addressbooks/"+n] = true
}
for _, dir := range disk {
if strings.HasPrefix(dir, "card-") && !configured[dir] {
@@ -101,7 +101,7 @@ func (b *Backend) ListAddressBooks(ctx context.Context) ([]carddav.AddressBook,
b.logger.Warn("listing shared address books", "error", err)
}
for _, sh := range shares {
if _, err := b.store.GetCollection(sh.Owner, "card-"+sh.AddressBookName); err != nil {
if _, err := b.store.GetCollection(sh.Owner, "addressbooks/"+sh.AddressBookName); err != nil {
continue // owner's address book no longer exists
}
localName := sharedBookName(sh.Owner, sh.AddressBookName)
@@ -138,7 +138,7 @@ func (b *Backend) GetAddressObject(ctx context.Context, objPath string, req *car
return nil, err
}
data, err := b.store.GetObject(owner, "card-"+realName, objID)
data, err := b.store.GetObject(owner, "addressbooks/"+realName, objID)
if err != nil {
return nil, webdav.NewHTTPError(http.StatusNotFound, err)
}
@@ -156,7 +156,7 @@ func (b *Backend) ListAddressObjects(ctx context.Context, bookPath string, req *
return nil, err
}
ids, err := b.store.ListObjects(owner, "card-"+realName)
ids, err := b.store.ListObjects(owner, "addressbooks/"+realName)
if err != nil {
return nil, err
}
@@ -209,7 +209,7 @@ func (b *Backend) DeleteAddressBook(ctx context.Context, bookPath string) error
if err := b.dbase.DeleteAddressBook(owner, realName); err != nil && err != db.ErrResourceNotFound {
return fmt.Errorf("unregistering address book: %w", err)
}
return b.store.DeleteCollection(owner, "card-"+realName)
return b.store.DeleteCollection(owner, "addressbooks/"+realName)
}
func (b *Backend) PutAddressObject(ctx context.Context, objPath string, card vcard.Card, opts *carddav.PutAddressObjectOptions) (*carddav.AddressObject, error) {
+4 -4
View File
@@ -8,11 +8,11 @@ import (
"strings"
"testing"
"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/store"
vcard "github.com/emersion/go-vcard"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
func newTestBackend(t *testing.T) (*Backend, *db.DB) {
+65 -38
View File
@@ -3,70 +3,97 @@ package config
import (
"fmt"
"os"
"strconv"
"gopkg.in/yaml.v3"
)
// Config is the top-level server configuration.
type Config struct {
Server ServerConfig
Auth AuthConfig
Storage StorageConfig
Logging LoggingConfig
Server ServerConfig `yaml:"server"`
Auth AuthConfig `yaml:"auth"`
Storage StorageConfig `yaml:"storage"`
TLS TLSConfig `yaml:"tls"`
Logging LoggingConfig `yaml:"logging"`
}
type ServerConfig struct {
Host string
Port int
BaseURL string
Host string `yaml:"host"`
Port int `yaml:"port"`
// Base URL used in DAV responses (e.g. https://dav.example.com)
BaseURL string `yaml:"base_url"`
}
type AuthConfig struct {
Realm string
// Realm shown in WWW-Authenticate header
Realm string `yaml:"realm"`
}
type StorageConfig struct {
DataDir string
// Root directory for all data
DataDir string `yaml:"data_dir"`
}
type TLSConfig struct {
Enabled bool `yaml:"enabled"`
CertFile string `yaml:"cert_file"`
KeyFile string `yaml:"key_file"`
}
type LoggingConfig struct {
Level string
Format string
Level string `yaml:"level"` // debug | info | warn | error
Format string `yaml:"format"` // text | json
}
// Load reads and parses a YAML config file.
func Load(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config %q: %w", path, err)
}
// Load reads and parses environment variables to create the configuration.
func Load() (*Config, error) {
cfg := &Config{}
if err := yaml.Unmarshal(data, cfg); err != nil {
return nil, fmt.Errorf("parsing config %q: %w", path, err)
}
cfg.applyDefaults()
return cfg, nil
return cfg, cfg.validate()
}
func (c *Config) applyDefaults() {
c.Server.Host = getEnv("NIDUS_HOST", "0.0.0.0")
c.Server.Port = getEnvInt("NIDUS_PORT", 8080)
c.Server.BaseURL = getEnv("NIDUS_BASE_URL", "")
if c.Server.Host == "" {
c.Server.Host = "0.0.0.0"
}
if c.Server.Port == 0 {
c.Server.Port = 8080
}
if c.Server.BaseURL == "" {
c.Server.BaseURL = fmt.Sprintf("http://%s:%d", c.Server.Host, c.Server.Port)
scheme := "http"
if c.TLS.Enabled {
scheme = "https"
}
c.Server.BaseURL = fmt.Sprintf("%s://%s:%d", scheme, c.Server.Host, c.Server.Port)
}
if c.Auth.Realm == "" {
c.Auth.Realm = "DAV Server"
}
if c.Storage.DataDir == "" {
c.Storage.DataDir = "./data"
}
if c.Logging.Level == "" {
c.Logging.Level = "info"
}
if c.Logging.Format == "" {
c.Logging.Format = "text"
}
}
c.Auth.Realm = getEnv("NIDUS_AUTH_REALM", "DAV Server")
c.Storage.DataDir = getEnv("NIDUS_DATA_DIR", "./data")
c.Logging.Level = getEnv("NIDUS_LOG_LEVEL", "info")
c.Logging.Format = getEnv("NIDUS_LOG_FORMAT", "text")
}
func getEnv(key string, defaultValue string) string {
if val := os.Getenv(key); val != "" {
return val
}
return defaultValue
}
func getEnvInt(key string, defaultValue int) int {
if val := os.Getenv(key); val != "" {
if intVal, err := strconv.Atoi(val); err == nil {
return intVal
func (c *Config) validate() error {
if c.TLS.Enabled {
if c.TLS.CertFile == "" || c.TLS.KeyFile == "" {
return fmt.Errorf("tls.cert_file and tls.key_file are required when tls is enabled")
}
}
return defaultValue
return nil
}
+3 -20
View File
@@ -27,20 +27,8 @@ import "regexp"
var tzidParamRe = regexp.MustCompile(`TZID=("?)([^";:\r\n]+)("?)`)
// tzidLineRe matches a standalone "TZID:<name>" property line, as found
// inside a VTIMEZONE component. The trailing "(\r?)" capture group is
// 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?)$`)
// inside a VTIMEZONE component.
var tzidLineRe = regexp.MustCompile(`(?m)^TZID:([^\r\n]+)$`)
// NormalizeTimeZones rewrites any recognized Windows timezone identifier
// in data to its IANA equivalent, leaving everything else (including
@@ -63,12 +51,7 @@ func NormalizeTimeZones(data []byte) []byte {
if !ok {
return m
}
// 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 []byte("TZID:" + iana)
})
return data
}
-33
View File
@@ -69,36 +69,3 @@ func TestNormalizeTimeZonesLeavesUnknownAndIANAZonesAlone(t *testing.T) {
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)
}
}
+27 -392
View File
@@ -7,8 +7,6 @@ package icssub
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
@@ -18,11 +16,11 @@ import (
ical "github.com/emersion/go-ical"
"git.arnef.de/arnef/nidus/internal/icalfix"
"github.com/yourusername/caldav-server/internal/icalfix"
)
// DefaultTTL is how long a fetched calendar is considered "fresh" before a
// Get will kick off a background refresh.
// DefaultTTL is how long a fetched calendar is cached before being
// re-fetched on the next access.
const DefaultTTL = 15 * time.Minute
// fetchTimeout bounds how long a single upstream request may take, so one
@@ -34,143 +32,54 @@ const fetchTimeout = 15 * time.Second
// response.
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 {
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
cal *ical.Calendar
err error
}
// Cache fetches remote ICS calendars over HTTP(S), keeping a shared
// in-memory copy per URL. Semantics:
//
// - 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.
// Cache fetches remote ICS calendars over HTTP(S), keeping a short-lived
// in-memory copy per URL so repeated renders (e.g. every month-view page
// load, or CalDAV client polling) don't re-fetch the same subscription
// from origin every time.
type Cache struct {
ttl time.Duration
client *http.Client
mu sync.Mutex
urls map[string]*entry // keyed by normalizeURL(url)
entries map[string]entry
}
// NewCache creates a Cache with the given TTL (use DefaultTTL if unsure).
func NewCache(ttl time.Duration) *Cache {
return &Cache{
ttl: ttl,
client: &http.Client{},
urls: make(map[string]*entry),
client: &http.Client{Timeout: fetchTimeout},
entries: make(map[string]entry),
}
}
// Get returns the most recently successfully-fetched calendar for url, or
// the most-recent fetch error if no successful copy exists yet (a
// background refresher may already be retrying).
// Get returns the parsed calendar fetched from url, using a cached copy
// if it's still within the TTL. If a fresh fetch fails but a previously
// fetched copy exists, the stale copy is returned instead of the error,
// so a transient network issue doesn't blank out the calendar entirely.
func (c *Cache) Get(url string) (*ical.Calendar, error) {
key := normalizeURL(url)
c.mu.Lock()
e := c.urls[key]
if e == nil {
e = &entry{url: url}
c.urls[key] = e
e, ok := c.entries[url]
fresh := ok && time.Since(e.fetchedAt) < c.ttl
c.mu.Unlock()
if fresh {
return e.cal, e.err
}
switch {
case e.cal == nil && e.lastErr == nil && !e.refreshing:
// Very first request for this URL: do a foreground fetch.
e.refreshing = true
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)
}
}
// 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)
cal, err := c.fetch(url)
c.mu.Lock()
e.fetchedAt = time.Now()
if err == nil {
e.cal = cal
e.lastErr = nil
} else {
e.lastErr = err
defer c.mu.Unlock()
if err != nil && ok && e.cal != nil {
return e.cal, nil
}
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
c.entries[url] = entry{fetchedAt: time.Now(), cal: cal, err: err}
return cal, err
}
// fetch downloads and parses url, translating a "webcal://" scheme (used
@@ -219,277 +128,3 @@ func normalizeURL(u string) string {
}
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
@@ -1,469 +0,0 @@
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
}
-200
View File
@@ -1,200 +0,0 @@
package store
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// Migrate restructures the data directory from the old format to the new unified format.
// It is idempotent and can be run multiple times safely.
//
// Old structure:
//
// data/files/<username>/
// data/<username>/cal-<name>/
// data/<username>/card-<name>/
//
// New structure:
//
// data/<username>/files/
// data/<username>/calendars/<name>/
// data/<username>/addressbooks/<name>/
func (s *Store) Migrate() error {
users, err := s.listUserDirectories()
if err != nil {
return fmt.Errorf("listing user directories: %w", err)
}
for _, user := range users {
if err := s.migrateUser(user); err != nil {
return fmt.Errorf("migrating user %q: %w", user, err)
}
}
return nil
}
// listUserDirectories returns all user directories in the data directory.
// It looks for directories that are NOT the old "files" directory,
// and also checks inside the old "files" directory for users who need migrating.
func (s *Store) listUserDirectories() ([]string, error) {
entries, err := os.ReadDir(s.rootDir)
if err != nil {
return nil, err
}
usersMap := make(map[string]bool)
for _, e := range entries {
if !e.IsDir() {
continue
}
name := e.Name()
// Skip the old files directory (will handle users inside it separately)
if name == "files" {
continue
}
usersMap[name] = true
}
// Also check the old files directory for users
filesDir := filepath.Join(s.rootDir, "files")
if filesEntries, err := os.ReadDir(filesDir); err == nil {
for _, e := range filesEntries {
if e.IsDir() {
usersMap[e.Name()] = true
}
}
}
var users []string
for user := range usersMap {
users = append(users, user)
}
return users, nil
}
// migrateUser migrates a single user's data from old to new structure.
func (s *Store) migrateUser(user string) error {
userDir := filepath.Join(s.rootDir, user)
// Create user directory if it doesn't exist (needed for WebDAV migration)
if err := os.MkdirAll(userDir, 0o755); err != nil {
return fmt.Errorf("creating user directory %q: %w", userDir, err)
}
// Migrate WebDAV files: files/<username> -> <username>/files
if err := s.migrateWebDAV(user); err != nil {
return err
}
// Migrate CalDAV calendars: cal-<name> -> calendars/<name>
if err := s.migrateCalendars(user, userDir); err != nil {
return err
}
// Migrate CardDAV address books: card-<name> -> addressbooks/<name>
if err := s.migrateAddressBooks(user, userDir); err != nil {
return err
}
return nil
}
// migrateWebDAV moves the old files/<username> directory to <username>/files.
func (s *Store) migrateWebDAV(user string) error {
oldPath := filepath.Join(s.rootDir, "files", user)
newPath := filepath.Join(s.rootDir, user, "files")
// Check if old directory exists and new doesn't
if _, err := os.Stat(oldPath); os.IsNotExist(err) {
return nil
}
if _, err := os.Stat(newPath); err == nil {
return nil // Already migrated
}
// Create parent directory if needed
if err := os.MkdirAll(filepath.Dir(newPath), 0o755); err != nil {
return fmt.Errorf("creating directory %q: %w", filepath.Dir(newPath), err)
}
// Move the directory
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("moving %q to %q: %w", oldPath, newPath, err)
}
return nil
}
// migrateCalendars moves old cal-<name> directories to calendars/<name>.
func (s *Store) migrateCalendars(user string, userDir string) error {
entries, err := os.ReadDir(userDir)
if err != nil {
return fmt.Errorf("reading user directory %q: %w", userDir, err)
}
var calendars []string
for _, e := range entries {
if e.IsDir() && strings.HasPrefix(e.Name(), "cal-") {
calendars = append(calendars, e.Name())
}
}
if len(calendars) == 0 {
return nil
}
calendarsDir := filepath.Join(userDir, "calendars")
if err := os.MkdirAll(calendarsDir, 0o755); err != nil {
return fmt.Errorf("creating calendars directory %q: %w", calendarsDir, err)
}
for _, calName := range calendars {
oldPath := filepath.Join(userDir, calName)
newPath := filepath.Join(calendarsDir, strings.TrimPrefix(calName, "cal-"))
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("moving calendar %q: %w", calName, err)
}
}
return nil
}
// migrateAddressBooks moves old card-<name> directories to addressbooks/<name>.
func (s *Store) migrateAddressBooks(user string, userDir string) error {
entries, err := os.ReadDir(userDir)
if err != nil {
return fmt.Errorf("reading user directory %q: %w", userDir, err)
}
var addressBooks []string
for _, e := range entries {
if e.IsDir() && strings.HasPrefix(e.Name(), "card-") {
addressBooks = append(addressBooks, e.Name())
}
}
if len(addressBooks) == 0 {
return nil
}
addressBooksDir := filepath.Join(userDir, "addressbooks")
if err := os.MkdirAll(addressBooksDir, 0o755); err != nil {
return fmt.Errorf("creating addressbooks directory %q: %w", addressBooksDir, err)
}
for _, bookName := range addressBooks {
oldPath := filepath.Join(userDir, bookName)
newPath := filepath.Join(addressBooksDir, strings.TrimPrefix(bookName, "card-"))
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("moving address book %q: %w", bookName, err)
}
}
return nil
}
-116
View File
@@ -1,116 +0,0 @@
package store
import (
"os"
"path/filepath"
"testing"
)
func TestMigrate(t *testing.T) {
tmpDir := t.TempDir()
// Create old structure
// WebDAV: files/<username>/
if err := os.MkdirAll(filepath.Join(tmpDir, "files", "alice"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "files", "alice", "test.txt"), []byte("test"), 0o644); err != nil {
t.Fatal(err)
}
// CalDAV: <username>/cal-<name>/
if err := os.MkdirAll(filepath.Join(tmpDir, "bob", "cal-work"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "bob", "cal-work", "evt.ics"), []byte("calendar"), 0o644); err != nil {
t.Fatal(err)
}
// CardDAV: <username>/card-<name>/
if err := os.MkdirAll(filepath.Join(tmpDir, "bob", "card-contacts"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "bob", "card-contacts", "vcard.vcf"), []byte("card"), 0o644); err != nil {
t.Fatal(err)
}
// Create store and migrate
st, err := NewStore(tmpDir)
if err != nil {
t.Fatal(err)
}
if err := st.Migrate(); err != nil {
t.Fatal(err)
}
// Verify WebDAV: <username>/files/
if _, err := os.Stat(filepath.Join(tmpDir, "alice", "files", "test.txt")); err != nil {
t.Errorf("alice files not migrated: %v", err)
}
// Verify CalDAV: <username>/calendars/<name>
if _, err := os.Stat(filepath.Join(tmpDir, "bob", "calendars", "work", "evt.ics")); err != nil {
t.Errorf("bob calendars not migrated: %v", err)
}
// Verify CardDAV: <username>/addressbooks/<name>
if _, err := os.Stat(filepath.Join(tmpDir, "bob", "addressbooks", "contacts", "vcard.vcf")); err != nil {
t.Errorf("bob addressbooks not migrated: %v", err)
}
// Verify old structure is gone
if _, err := os.Stat(filepath.Join(tmpDir, "files", "alice")); err == nil {
t.Error("old files directory not removed")
}
if _, err := os.Stat(filepath.Join(tmpDir, "bob", "cal-work")); err == nil {
t.Error("old cal- directory not removed")
}
if _, err := os.Stat(filepath.Join(tmpDir, "bob", "card-contacts")); err == nil {
t.Error("old card- directory not removed")
}
}
func TestMigrateIdempotent(t *testing.T) {
tmpDir := t.TempDir()
// Create new structure
if err := os.MkdirAll(filepath.Join(tmpDir, "alice", "files"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "alice", "files", "test.txt"), []byte("test"), 0o644); err != nil {
t.Fatal(err)
}
st, err := NewStore(tmpDir)
if err != nil {
t.Fatal(err)
}
// Run migration twice
if err := st.Migrate(); err != nil {
t.Fatal(err)
}
if err := st.Migrate(); err != nil {
t.Fatal(err)
}
// Verify data still there
if _, err := os.Stat(filepath.Join(tmpDir, "alice", "files", "test.txt")); err != nil {
t.Errorf("data not preserved: %v", err)
}
}
func TestMigrateMissingDirectories(t *testing.T) {
tmpDir := t.TempDir()
st, err := NewStore(tmpDir)
if err != nil {
t.Fatal(err)
}
// Should not error on empty directory
if err := st.Migrate(); err != nil {
t.Errorf("unexpected error: %v", err)
}
}
+83 -24
View File
@@ -48,26 +48,15 @@ func (s *Store) lockFor(user string) *sync.RWMutex {
return l
}
// collectionPath returns the filesystem path for a collection in the new unified format.
// Calendar collections: <username>/calendars/<name>
// Address book collections: <username>/addressbooks/<name>
// WebDAV collections: <username>/files (all files in one directory)
// collectionPath returns the filesystem path for a collection.
func (s *Store) collectionPath(user, collection string) string {
userDir := filepath.Join(s.rootDir, sanitize(user))
if strings.HasPrefix(collection, "cal-") {
return filepath.Join(userDir, "calendars", strings.TrimPrefix(collection, "cal-"))
return filepath.Join(s.rootDir, sanitize(user), sanitize(collection))
}
if strings.HasPrefix(collection, "card-") {
return filepath.Join(userDir, "addressbooks", strings.TrimPrefix(collection, "card-"))
}
if collection == "files" {
return filepath.Join(userDir, "files")
}
return filepath.Join(userDir, sanitize(collection))
// unifiedCollectionPath returns the filesystem path for a collection with the
// new unified structure: data/<username>/<type>/<name>/
func (s *Store) unifiedCollectionPath(user, typePath, name string) string {
return filepath.Join(s.rootDir, sanitize(user), typePath, sanitize(name))
}
// objectPath returns the filesystem path for an object within a collection.
@@ -80,12 +69,28 @@ func (s *Store) EnsureCollection(user, collection string) error {
l := s.lockFor(user)
l.Lock()
defer l.Unlock()
dir := s.collectionPath(user, collection)
var dir string
if strings.Contains(collection, "/") {
// It's a full path like "calendars/work"
dir = s.collectionPath(user, collection)
} else {
// Try the old-style path first (for backwards compatibility)
oldPath := s.collectionPath(user, collection)
_, err := os.Stat(oldPath)
if err == nil {
dir = oldPath
} else {
// For new paths, we need to try both structure styles:
// data/<username>/<type>/<name>
dir = s.collectionPath(user, collection)
}
}
return os.MkdirAll(dir, 0o755)
}
// ListCollections returns all collection names for a user.
// Returns both old-style (cal-*, card-*) and new-style (calendars/*, addressbooks/*) collections.
func (s *Store) ListCollections(user string) ([]string, error) {
l := s.lockFor(user)
l.RLock()
@@ -103,8 +108,16 @@ func (s *Store) ListCollections(user string) ([]string, error) {
var names []string
for _, e := range entries {
if e.IsDir() {
name := e.Name()
names = append(names, name)
// Handle the new nested structure (calendars/addressbooks/)
// and old flat structure for backwards compatibility
if strings.HasPrefix(e.Name(), "calendars/") || strings.HasPrefix(e.Name(), "addressbooks/") {
// Extract name from nested path
parts := strings.Split(e.Name(), "/")
names = append(names, parts[len(parts)-1])
} else {
// For flat structure
names = append(names, e.Name())
}
}
}
return names, nil
@@ -115,7 +128,25 @@ func (s *Store) GetCollection(user, collection string) (os.FileInfo, error) {
l := s.lockFor(user)
l.RLock()
defer l.RUnlock()
info, err := os.Stat(s.collectionPath(user, collection))
var path string
if strings.Contains(collection, "/") {
// It's a full path like "calendars/work"
path = s.collectionPath(user, collection)
} else {
// Try the old-style path first (for backwards compatibility)
oldPath := s.collectionPath(user, collection)
_, err := os.Stat(oldPath)
if err == nil {
path = oldPath
} else {
// For new paths, we need to try both structure styles:
// data/<username>/<type>/<name>
path = s.collectionPath(user, collection)
}
}
info, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return nil, ErrNotFound
}
@@ -174,7 +205,17 @@ func (s *Store) ListObjects(user, collection string) ([]string, error) {
l.RLock()
defer l.RUnlock()
dir := s.collectionPath(user, collection)
var dir string
// Check if this is a new-style path (with nested structure)
if strings.Contains(collection, "/") {
// It's a full path like "calendars/work"
dir = s.collectionPath(user, collection)
} else {
// It's an old-style path
dir = s.collectionPath(user, collection)
}
entries, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return nil, ErrNotFound
@@ -210,7 +251,25 @@ func (s *Store) DeleteCollection(user, collection string) error {
l := s.lockFor(user)
l.Lock()
defer l.Unlock()
err := os.RemoveAll(s.collectionPath(user, collection))
var path string
if strings.Contains(collection, "/") {
// It's a full path like "calendars/work"
path = s.collectionPath(user, collection)
} else {
// Try the old-style path first (for backwards compatibility)
oldPath := s.collectionPath(user, collection)
_, err := os.Stat(oldPath)
if err == nil {
path = oldPath
} else {
// For new paths, we need to try both structure styles:
// data/<username>/<type>/<name>
path = s.collectionPath(user, collection)
}
}
err := os.RemoveAll(path)
return err
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"sync"
"testing"
"git.arnef.de/arnef/nidus/internal/store"
"github.com/yourusername/caldav-server/internal/store"
)
func TestStoreRoundTrip(t *testing.T) {
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"net/http"
"strings"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// handleAccount serves GET /account: the current user's own profile and
+60 -215
View File
@@ -15,13 +15,11 @@ import (
"strings"
"time"
"git.arnef.de/arnef/nidus/internal/birthdays"
"git.arnef.de/arnef/nidus/internal/db"
"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"
ical "github.com/emersion/go-ical"
"github.com/yourusername/caldav-server/internal/birthdays"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/icalfix"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// eventIDRe validates an event's object ID as it appears in a URL path
@@ -296,9 +294,9 @@ func parseWeekStart(r *http.Request) time.Time {
// buildMonthView loads every event from every calendar visible to
// username (own + shared), then places each occurrence's days onto a
// 6-week grid covering the requested month (plus enough leading/trailing
// days of neighboring months to fill full weeks). Recurring events (RRULE)
// are expanded: every occurrence falling in the grid's window is placed
// (see eventOccurrenceDays), not just the event's base DTSTART/DTEND.
// days of neighboring months to fill full weeks). Recurring events
// (RRULE) are not expanded — only an event's own DTSTART/DTEND span is
// considered.
func (s *Server) buildMonthView(username string, year int, month time.Month) (templates.MonthViewData, error) {
loc := time.Local
first := time.Date(year, month, 1, 0, 0, 0, 0, loc)
@@ -473,24 +471,33 @@ func (s *Server) collectCalendarEvents(username string, gridStart, gridEnd time.
if err != nil {
continue
}
ev, err := firstEventFromICS(data)
form, err := eventFormFromICS(id, data)
if err != nil {
s.logger.Warn("decoding calendar object", "calendar", entry.Name, "id", id, "error", err)
continue
}
daysSet := eventOccurrenceDays(ev, gridStart, gridEnd, loc, dayIndex)
if len(daysSet) == 0 {
startDay, endDay, err := eventDayRange(form, loc)
if err != nil {
continue
}
form, err := eventFormFromComponent(id, ev)
if err != nil {
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 {
continue
}
timeText := ""
if !form.AllDay {
timeText = form.StartTime
}
for idx := range daysSet {
days[idx].Events = append(days[idx].Events, templates.EventSummary{
ID: id,
CalRef: entry.Ref,
@@ -520,76 +527,25 @@ 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)
}
// eventOccurrenceDays returns the set of grid day indices (into
// dayIndex) that event ev occupies within [gridStart, gridEnd]. A plain
// event occupies its DTSTART..DTEND day span. A recurring event (RRULE)
// 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)
// eventDayRange returns the inclusive [start, end] calendar-day span an
// event occupies, in loc, for placing it on the month grid.
func eventDayRange(form templates.EventFormData, loc *time.Location) (start, end time.Time, err error) {
start, err = time.ParseInLocation(dateLayout, form.StartDate, loc)
if err != nil {
return nil
return time.Time{}, time.Time{}, err
}
// Per-occurrence duration: the DTSTART..DTEND span of the base event
// (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)
endDate := form.EndDate
if endDate == "" {
endDate = form.StartDate
}
}
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()
end, err = time.ParseInLocation(dateLayout, endDate, loc)
if err != nil {
return ical.Event{}, err
return time.Time{}, time.Time{}, err
}
events := calendar.Events()
if len(events) == 0 {
return ical.Event{}, fmt.Errorf("no VEVENT in calendar object")
if end.Before(start) {
end = start
}
return events[0], nil
return start, end, nil
}
func (s *Server) handleEventNew(w http.ResponseWriter, r *http.Request) {
@@ -680,113 +636,6 @@ 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) {
username := userFromContext(r.Context())
ref := r.PathValue("ref")
@@ -1350,46 +1199,41 @@ func (s *Server) addBirthdayEvents(username string, entry calendarEntry, gridSta
}
// addICSEvents fetches entry's remote ICS/webcal calendar (via s.icsCache,
// which uses stale-while-revalidate so a month-view render never blocks on
// network I/O) and places each Series' day-occurrences onto the grid.
//
// A "Series" is one UID group in the feed: the base (RRULE-carrying)
// 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).
// which caches it for a while so every month-view render doesn't re-fetch
// from origin) and places each VEVENT's occurrence onto the month 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
// event's LinkURL is left pointing nowhere useful ("#").
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)
if err != nil {
return err
}
for _, series := range icssub.GroupSeries(cal) {
if series.Base == nil && len(series.Instances) == 0 {
continue
}
id := series.ID()
occByDay := series.OccurrencesIn(gridStart, gridEnd, loc)
if len(occByDay) == 0 {
continue
}
anchor := series.Anchor()
baseForm, err := eventFormFromComponent(id, *anchor)
const totalDays = 42
for i, ev := range cal.Events() {
id := fmt.Sprintf("ics-%d", i)
form, err := eventFormFromComponent(id, ev)
if err != nil {
continue
}
for dayStr, ev := range occByDay {
idx, ok := dayIndex[dayStr]
if !ok {
startDay, endDay, err := eventDayRange(form, loc)
if err != nil {
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
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 {
continue
}
timeText := ""
if !form.AllDay {
@@ -1402,6 +1246,7 @@ func (s *Server) addICSEvents(entry calendarEntry, gridStart, gridEnd time.Time,
Summary: form.Summary,
TimeText: timeText,
AllDay: form.AllDay,
LinkURL: "#",
})
}
}
+47 -58
View File
@@ -14,12 +14,10 @@ import (
"sort"
"strconv"
"strings"
"time"
"git.arnef.de/arnef/nidus/internal/birthdays"
"git.arnef.de/arnef/nidus/internal/store"
"git.arnef.de/arnef/nidus/internal/web/templates"
vcard "github.com/emersion/go-vcard"
"github.com/yourusername/caldav-server/internal/store"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// contactIDRe validates a contact's object ID as it appears in a URL path
@@ -241,8 +239,7 @@ func (s *Server) handleContactEdit(w http.ResponseWriter, r *http.Request) {
// contactFormInput holds the parsed, validated-ish values submitted by the
// contact form, before they're translated into vCard fields.
type contactFormInput struct {
Forename string
Surname string
FullName string
Organization string
Note string
Birthday string
@@ -287,8 +284,7 @@ func parseContactForm(r *http.Request) (contactFormInput, error) {
get := func(key string) []string { return form[key] }
in := contactFormInput{
Forename: strings.TrimSpace(formValue(get("forename"), 0)),
Surname: strings.TrimSpace(formValue(get("surname"), 0)),
FullName: strings.TrimSpace(formValue(get("full_name"), 0)),
Organization: strings.TrimSpace(formValue(get("organization"), 0)),
Note: strings.TrimSpace(formValue(get("note"), 0)),
Birthday: strings.TrimSpace(formValue(get("birthday"), 0)),
@@ -313,13 +309,25 @@ func parseContactForm(r *http.Request) (contactFormInput, error) {
in.Emails = append(in.Emails, templates.LabeledValue{Type: formValue(emailTypes, i), Value: v})
}
addrTypes, addrValues := get("address_type"), get("address_value")
for i, v := range addrValues {
v = strings.TrimSpace(v)
if v == "" {
addrTypes := get("address_type")
streets := get("address_street")
cities := get("address_city")
postalCodes := get("address_postal_code")
regions := get("address_region")
countries := get("address_country")
for i := range streets {
street := strings.TrimSpace(formValue(streets, i))
city := strings.TrimSpace(formValue(cities, i))
postalCode := strings.TrimSpace(formValue(postalCodes, i))
region := strings.TrimSpace(formValue(regions, i))
country := strings.TrimSpace(formValue(countries, i))
if street == "" && city == "" && postalCode == "" && region == "" && country == "" {
continue
}
in.Addresses = append(in.Addresses, templates.AddressValue{Type: formValue(addrTypes, i), Value: v})
in.Addresses = append(in.Addresses, templates.AddressValue{
Type: formValue(addrTypes, i), Street: street, City: city,
Region: region, PostalCode: postalCode, Country: country,
})
}
if r.MultipartForm != nil {
@@ -350,12 +358,11 @@ func (s *Server) saveContactFromForm(w http.ResponseWriter, r *http.Request, use
return
}
if in.Forename == "" && in.Surname == "" {
if in.FullName == "" {
form := templates.ContactFormData{
Book: book,
ID: id,
Forename: in.Forename,
Surname: in.Surname,
FullName: in.FullName,
Organization: in.Organization,
Note: in.Note,
Birthday: in.Birthday,
@@ -364,7 +371,7 @@ func (s *Server) saveContactFromForm(w http.ResponseWriter, r *http.Request, use
Addresses: ensureAtLeastOne(in.Addresses),
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = templates.ContactForm(username, form, "Name is required").Render(context.Background(), w)
_ = templates.ContactForm(username, form, "Full name is required").Render(context.Background(), w)
return
}
@@ -415,10 +422,16 @@ func buildCard(uid string, in contactFormInput, existingPhoto string) vcard.Card
if uid != "" {
card.SetValue(vcard.FieldUID, uid)
}
if fn := strings.TrimSpace(in.Forename + " " + in.Surname); fn != "" {
card.SetValue(vcard.FieldFormattedName, fn)
card.SetValue(vcard.FieldFormattedName, in.FullName)
name := &vcard.Name{}
parts := strings.Fields(in.FullName)
if len(parts) > 0 {
name.GivenName = parts[0]
}
if len(parts) > 1 {
name.FamilyName = strings.Join(parts[1:], " ")
}
name := &vcard.Name{GivenName: in.Forename, FamilyName: in.Surname}
card.SetName(name)
if in.Organization != "" {
@@ -446,7 +459,14 @@ func buildCard(uid string, in contactFormInput, existingPhoto string) vcard.Card
card.Add(vcard.FieldEmail, f)
}
for _, a := range in.Addresses {
addr := &vcard.Address{Field: &vcard.Field{}, StreetAddress: a.Value}
addr := &vcard.Address{
Field: &vcard.Field{},
StreetAddress: a.Street,
Locality: a.City,
Region: a.Region,
PostalCode: a.PostalCode,
Country: a.Country,
}
if a.Type != "" {
addr.Params = vcard.Params{vcard.ParamType: {a.Type}}
}
@@ -492,27 +512,6 @@ func photoDataURL(card vcard.Card) string {
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 {
fields := card[key]
out := make([]templates.LabeledValue, 0, len(fields))
@@ -534,8 +533,10 @@ func addressValues(card vcard.Card) []templates.AddressValue {
if a.Params != nil {
typ = a.Params.Get(vcard.ParamType)
}
value := strings.Join([]string{a.StreetAddress, a.Locality, a.Region, a.PostalCode, a.Country}, ", ")
out = append(out, templates.AddressValue{Type: typ, Value: value})
out = append(out, templates.AddressValue{
Type: typ, Street: a.StreetAddress, City: a.Locality,
Region: a.Region, PostalCode: a.PostalCode, Country: a.Country,
})
}
return out
}
@@ -546,25 +547,13 @@ func contactFormFromCard(book, id string, data []byte) (templates.ContactFormDat
if err != nil {
return templates.ContactFormData{}, err
}
var forename, surname string
if n := card.Name(); n != nil && (n.GivenName != "" || n.FamilyName != "") {
forename, surname = n.GivenName, n.FamilyName
} else if fn := strings.TrimSpace(card.PreferredValue(vcard.FieldFormattedName)); fn != "" {
parts := strings.Fields(fn)
if len(parts) > 1 {
forename, surname = parts[0], strings.Join(parts[1:], " ")
} else {
forename = parts[0]
}
}
return templates.ContactFormData{
Book: book,
ID: id,
Forename: forename,
Surname: surname,
FullName: card.PreferredValue(vcard.FieldFormattedName),
Organization: card.PreferredValue(vcard.FieldOrganization),
Note: card.PreferredValue(vcard.FieldNote),
Birthday: birthdayInputValue(card.PreferredValue(vcard.FieldBirthday)),
Birthday: card.PreferredValue(vcard.FieldBirthday),
PhotoDataURL: photoDataURL(card),
Phones: ensureAtLeastOne(labeledValues(card, vcard.FieldTelephone)),
Emails: ensureAtLeastOne(labeledValues(card, vcard.FieldEmail)),
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"fmt"
"net/http"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/web/templates"
)
func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
-209
View File
@@ -1,209 +0,0 @@
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())
}
}
+4 -48
View File
@@ -12,7 +12,7 @@ import (
"path/filepath"
"strings"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// maxUploadMemory bounds how much of a multipart upload is buffered in
@@ -24,7 +24,7 @@ const maxUploadMemory = 32 << 20 // 32 MiB
// (internal/webdav) serves at /files/, so the web UI is just another view
// onto the same files.
func (s *Server) filesRoot(username string) string {
return filepath.Join(s.cfg.Storage.DataDir, username, "files")
return filepath.Join(s.cfg.Storage.DataDir, "files", username)
}
// sanitizeRelPath cleans a slash-separated relative path (as received from
@@ -142,7 +142,7 @@ func (s *Server) handleFilesMkdir(w http.ResponseWriter, r *http.Request, root,
}
name := strings.TrimSpace(r.PostForm.Get("name"))
if !resourceNameRe.MatchString(name) {
http.Error(w, "name must be 1-64 letters, digits, dots, '-' or '_'", http.StatusBadRequest)
http.Error(w, "name must be 1-64 letters, digits, '-' or '_'", http.StatusBadRequest)
return
}
@@ -211,16 +211,6 @@ func (s *Server) handleFilesGet(w http.ResponseWriter, r *http.Request, username
return
}
// Determine sort order (name asc/desc) from query param, default to asc
sortBy := r.URL.Query().Get("sort_by")
sortDir := r.URL.Query().Get("sort_dir")
if sortBy == "" {
sortBy = "name"
}
if sortDir == "" {
sortDir = "asc"
}
// os.ReadDir already returns entries sorted by filename, so filtering
// into two passes keeps each group (directories, then files)
// alphabetically sorted while grouping directories first.
@@ -244,40 +234,6 @@ func (s *Server) handleFilesGet(w http.ResponseWriter, r *http.Request, username
files = append(files, entry)
}
}
// Sort entries based on sortBy and sortDir
less := func(i, j templates.FileEntry) bool {
switch sortBy {
case "name":
if sortDir == "desc" {
return i.Name > j.Name
}
return i.Name < j.Name
default:
if sortDir == "desc" {
return i.ModTime > j.ModTime
}
return i.ModTime < j.ModTime
}
}
// Sort dirs
for i := 0; i < len(dirs)-1; i++ {
for j := i + 1; j < len(dirs); j++ {
if less(dirs[j], dirs[i]) {
dirs[i], dirs[j] = dirs[j], dirs[i]
}
}
}
// Sort files
for i := 0; i < len(files)-1; i++ {
for j := i + 1; j < len(files); j++ {
if less(files[j], files[i]) {
files[i], files[j] = files[j], files[i]
}
}
}
entries := append(dirs, files...)
var breadcrumbs []templates.Breadcrumb
@@ -292,7 +248,7 @@ func (s *Server) handleFilesGet(w http.ResponseWriter, r *http.Request, username
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = templates.FilesPage(username, breadcrumbs, entries, relPath, sortBy, sortDir).Render(context.Background(), w)
_ = templates.FilesPage(username, breadcrumbs, entries, relPath).Render(context.Background(), w)
}
func (s *Server) handleFilesUpload(w http.ResponseWriter, r *http.Request, root, fullPath string) {
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"net/http"
"strings"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// icsURLValid does a light sanity check on a subscription URL: it must be
-272
View File
@@ -1,272 +0,0 @@
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]
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"net/http"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/web/templates"
)
func renderLogin(w http.ResponseWriter, errMsg string) {
+3 -4
View File
@@ -6,14 +6,13 @@ import (
"regexp"
"strings"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// resourceNameRe restricts calendar/address book names to characters that
// are safe as both a URL path segment and a filesystem directory name.
// Includes dots for hidden files/folders (Unix convention).
var resourceNameRe = regexp.MustCompile(`^[a-zA-Z0-9._-]{1,64}$`)
var resourceNameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
// hexColorRe validates the 6-digit hex color format produced by an HTML
// <input type="color">, e.g. "#3b82f6".
+7 -15
View File
@@ -10,10 +10,10 @@ import (
"net/http"
"strings"
"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"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/icssub"
"github.com/yourusername/caldav-server/internal/store"
)
// Server holds the dependencies needed by the web UI handlers.
@@ -25,16 +25,9 @@ type Server struct {
icsCache *icssub.Cache
}
// NewServer constructs a web UI Server. icsCache may be nil, in which
// case a private default-TTL cache is created — prefer sharing a single
// *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}
// NewServer constructs a web UI Server.
func NewServer(cfg *config.Config, st *store.Store, dbase *db.DB, logger *slog.Logger) *Server {
return &Server{cfg: cfg, store: st, dbase: dbase, logger: logger, icsCache: icssub.NewCache(icssub.DefaultTTL)}
}
// Handler returns the http.Handler serving the web UI, mounted at "/web/"
@@ -72,7 +65,6 @@ func (s *Server) Handler(staticFS http.FileSystem) http.Handler {
mux.HandleFunc("/calendar", s.requireLogin(s.handleCalendarMonth))
mux.HandleFunc("/calendar/week", s.requireLogin(s.handleCalendarWeek))
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}/export", s.requireLogin(s.handleCalendarExportAll))
mux.HandleFunc("/calendar/{ref}/{id}/edit", s.requireLogin(s.handleEventEdit))
+4 -27
View File
@@ -1,7 +1,6 @@
package web
import (
"fmt"
"io"
"log/slog"
"net/http"
@@ -11,11 +10,10 @@ import (
"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/store"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
func newTestServer(t *testing.T) *Server {
@@ -49,7 +47,7 @@ func newTestServer(t *testing.T) *Server {
t.Fatalf("CreateCalendar bob/personal: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(cfg, st, dbase, logger, nil)
return NewServer(cfg, st, dbase, logger)
}
// loginAs performs a login request against handler and returns the
@@ -318,24 +316,3 @@ func TestAccountChangePassword(t *testing.T) {
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)
}
}
}
+2 -2
View File
@@ -46,7 +46,7 @@ func (s *Server) setSessionCookie(w http.ResponseWriter, token string) {
Value: token,
Path: "/",
HttpOnly: true,
Secure: true,
Secure: s.cfg.TLS.Enabled,
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(7 * 24 * time.Hour),
})
@@ -58,7 +58,7 @@ func (s *Server) clearSessionCookie(w http.ResponseWriter) {
Value: "",
Path: "/",
HttpOnly: true,
Secure: true,
Secure: s.cfg.TLS.Enabled,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"net/http"
"strings"
"git.arnef.de/arnef/nidus/internal/web/templates"
"github.com/yourusername/caldav-server/internal/web/templates"
)
// handleCalendarShare handles POST (create/update share) and DELETE
+4 -126
View File
@@ -3,7 +3,6 @@ package templates
import "fmt"
import "strconv"
import "strings"
import "time"
// CalendarSummary is one calendar (own or shared) shown in the combined
// month view's legend.
@@ -25,9 +24,9 @@ type EventSummary struct {
Summary string
TimeText string // e.g. "14:00" or "" for all-day events
AllDay bool
// LinkURL overrides the default "/web/calendar/{CalRef}/{ID}" (detail
// view) link target, used by virtual/read-only calendars (e.g.
// birthdays) that don't have an editable event object of their own.
// LinkURL overrides the default "/web/calendar/{CalRef}/{ID}/edit"
// link target, used by virtual/read-only calendars (e.g. birthdays)
// that don't have an editable event object of their own.
LinkURL string
}
@@ -101,14 +100,6 @@ type EventFormData struct {
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) {
@Layout("Calendar", username) {
<div class="flex items-center justify-between mb-6 gap-4 flex-wrap">
@@ -310,7 +301,7 @@ func eventLinkURL(ev EventSummary) string {
if ev.LinkURL != "" {
return ev.LinkURL
}
return "/web/calendar/" + ev.CalRef + "/" + ev.ID
return "/web/calendar/" + ev.CalRef + "/" + ev.ID + "/edit"
}
// eventTextColor returns a color derived from hex, darkened if needed so
@@ -364,119 +355,6 @@ 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) {
@Layout("Calendar", username) {
<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,54 +33,6 @@ 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) {
if got := eventTextColor(""); got != colorOrDefault("") {
t.Errorf("eventTextColor(\"\") = %s, want the same default colorOrDefault returns", got)
+41 -47
View File
@@ -26,11 +26,14 @@ type LabeledValue struct {
Value string
}
// AddressValue is one ADR entry with its TYPE parameter; the full address
// is captured as a single free-form string.
// AddressValue is one ADR entry with its TYPE parameter.
type AddressValue struct {
Type string
Value string
Street string
City string
Region string
PostalCode string
Country string
}
// ContactFormData pre-fills the create/edit contact form. Phones, Emails,
@@ -39,8 +42,7 @@ type AddressValue struct {
type ContactFormData struct {
Book string
ID string // empty when creating a new contact
Forename string
Surname string
FullName string
Organization string
Birthday string // "YYYY-MM-DD", empty if not set
Note string
@@ -156,50 +158,49 @@ templ ContactsList(username, book string, contacts []ContactSummary) {
}
}
// typeSelect renders the TYPE dropdown shared by email/address rows.
// typeSelect renders the TYPE dropdown shared by phone/email/address rows.
templ typeSelect(name, selected string) {
<select name={ name } class="rounded-md border-gray-300 border px-2 py-1.5 text-sm">
<option value="" selected?={ selected == "" }>Other</option>
<option value="home" selected?={ selected == "home" }>Home</option>
<option value="work" selected?={ selected == "work" }>Work</option>
</select>
}
// phoneTypeSelect renders the phone TYPE dropdown. An unspecified number is
// shown as "Mobile" (the vCard "cell" type), matching how mobile clients
// label a contact's main number.
templ phoneTypeSelect(name, selected string) {
<select name={ name } class="rounded-md border-gray-300 border px-2 py-1.5 text-sm">
<option value="cell" selected?={ selected == "cell" || selected == "" }>Mobile</option>
<option value="home" selected?={ selected == "home" }>Home</option>
<option value="work" selected?={ selected == "work" }>Work</option>
<option value="" selected?={ selected == "" }>Sonstige</option>
<option value="home" selected?={ selected == "home" }>Privat</option>
<option value="work" selected?={ selected == "work" }>Geschäftlich</option>
</select>
}
templ phoneRow(p LabeledValue) {
<div class="form-row flex gap-2 items-center">
@phoneTypeSelect("phone_type", p.Type)
<input name="phone_value" type="tel" value={ p.Value } placeholder="Phone number"
@typeSelect("phone_type", p.Type)
<input name="phone_value" type="tel" value={ p.Value } placeholder="Telefonnummer"
class="flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs shrink-0">Remove</button>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs shrink-0">Entfernen</button>
</div>
}
templ emailRow(p LabeledValue) {
<div class="form-row flex gap-2 items-center">
@typeSelect("email_type", p.Type)
<input name="email_value" type="email" value={ p.Value } placeholder="Email address"
<input name="email_value" type="email" value={ p.Value } placeholder="E-Mail-Adresse"
class="flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs shrink-0">Remove</button>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs shrink-0">Entfernen</button>
</div>
}
templ addressRow(a AddressValue) {
<div class="form-row flex gap-2 items-center">
<div class="form-row grid grid-cols-2 gap-2 items-start bg-gray-50 rounded-md p-3">
<div class="col-span-2">
@typeSelect("address_type", a.Type)
<input name="address_value" type="text" value={ a.Value } placeholder="Street, city, postal code, country"
class="flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs shrink-0">Remove</button>
</div>
<input name="address_street" type="text" value={ a.Street } placeholder="Straße und Hausnummer"
class="col-span-2 rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<input name="address_city" type="text" value={ a.City } placeholder="Stadt"
class="rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<input name="address_postal_code" type="text" value={ a.PostalCode } placeholder="PLZ"
class="rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<input name="address_region" type="text" value={ a.Region } placeholder="Bundesland/Region"
class="rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<input name="address_country" type="text" value={ a.Country } placeholder="Land"
class="rounded-md border-gray-300 border px-2 py-1.5 text-sm"/>
<button type="button" class="remove-row-btn text-red-600 hover:underline text-xs col-span-2 text-left">Entfernen</button>
</div>
}
@@ -229,74 +230,67 @@ templ ContactForm(username string, data ContactFormData, errMsg string) {
<img id="photo-preview" src="" alt="" class="w-20 h-20 rounded-full object-cover hidden"/>
<div class="space-y-1">
<label class="cursor-pointer inline-block bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
Choose photo
Foto wählen
<input id="photo-input" name="photo" type="file" accept="image/*" class="hidden"/>
</label>
if data.PhotoDataURL != "" {
<label class="flex items-center gap-1 text-xs text-gray-500">
<input id="remove-photo" name="remove_photo" type="checkbox" value="1"/>
Remove photo
Foto entfernen
</label>
}
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label class="block text-sm font-medium text-gray-700">First name</label>
<input name="forename" type="text" value={ data.Forename }
<label class="block text-sm font-medium text-gray-700">Full name</label>
<input name="full_name" type="text" required value={ data.FullName }
class="mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm"/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Last name</label>
<input name="surname" type="text" value={ data.Surname }
class="mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm"/>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Organization</label>
<input name="organization" type="text" value={ data.Organization }
class="mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm"/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Birthday</label>
<label class="block text-sm font-medium text-gray-700">Geburtstag</label>
<input name="birthday" type="date" value={ data.Birthday }
class="mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm"/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Phones</label>
<label class="block text-sm font-medium text-gray-700 mb-2">Telefonnummern</label>
<div id="phones-container" class="space-y-2">
for _, p := range data.Phones {
@phoneRow(p)
}
</div>
<button type="button" data-add-target="phones-container" class="add-row-btn mt-2 text-sm text-indigo-600 hover:underline">
+ Add phone number
+ Telefonnummer hinzufügen
</button>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Emails</label>
<label class="block text-sm font-medium text-gray-700 mb-2">E-Mail-Adressen</label>
<div id="emails-container" class="space-y-2">
for _, e := range data.Emails {
@emailRow(e)
}
</div>
<button type="button" data-add-target="emails-container" class="add-row-btn mt-2 text-sm text-indigo-600 hover:underline">
+ Add email address
+ E-Mail-Adresse hinzufügen
</button>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Addresses</label>
<label class="block text-sm font-medium text-gray-700 mb-2">Adressen</label>
<div id="addresses-container" class="space-y-2">
for _, a := range data.Addresses {
@addressRow(a)
}
</div>
<button type="button" data-add-target="addresses-container" class="add-row-btn mt-2 text-sm text-indigo-600 hover:underline">
+ Add address
+ Adresse hinzufügen
</button>
</div>
+215 -249
View File
@@ -34,11 +34,14 @@ type LabeledValue struct {
Value string
}
// AddressValue is one ADR entry with its TYPE parameter; the full address
// is captured as a single free-form string.
// AddressValue is one ADR entry with its TYPE parameter.
type AddressValue struct {
Type string
Value string
Street string
City string
Region string
PostalCode string
Country string
}
// ContactFormData pre-fills the create/edit contact form. Phones, Emails,
@@ -47,8 +50,7 @@ type AddressValue struct {
type ContactFormData struct {
Book string
ID string // empty when creating a new contact
Forename string
Surname string
FullName string
Organization string
Birthday string // "YYYY-MM-DD", empty if not set
Note string
@@ -113,7 +115,7 @@ func ContactsHome(username string, books []AddressBookSummary) templ.Component {
var templ_7745c5c3_Var3 templ.SafeURL
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + b.Name))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 65, Col: 52}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 67, Col: 52}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -126,7 +128,7 @@ func ContactsHome(username string, books []AddressBookSummary) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(b.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 65, Col: 115}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 67, Col: 115}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -139,7 +141,7 @@ func ContactsHome(username string, books []AddressBookSummary) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d contact(s)", b.Count))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 66, Col: 73}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 68, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -202,7 +204,7 @@ func avatar(photoDataURL, sizeClass string) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.ResolveAttributeValue(photoDataURL)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 79, Col: 25}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 81, Col: 25}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
if templ_7745c5c3_Err != nil {
@@ -293,7 +295,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(book)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 92, Col: 45}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 94, Col: 45}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
@@ -306,7 +308,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var15 templ.SafeURL
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/new"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 95, Col: 57}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 97, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
@@ -319,7 +321,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var16 templ.SafeURL
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/export"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 99, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 101, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
@@ -332,7 +334,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var17 templ.SafeURL
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/import"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 105, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 107, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -358,7 +360,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var18 templ.SafeURL
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/" + c.ID + "/edit"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 135, Col: 75}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 137, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -371,7 +373,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(c.FullName)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 135, Col: 130}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 137, Col: 130}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
@@ -384,7 +386,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(c.Organization)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 137, Col: 92}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 139, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -397,7 +399,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(c.Phone)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 138, Col: 91}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 140, Col: 91}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
@@ -410,7 +412,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(c.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 139, Col: 85}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 141, Col: 85}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil {
@@ -423,7 +425,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var23 templ.SafeURL
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/" + c.ID + "/export"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 141, Col: 77}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 143, Col: 77}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil {
@@ -436,7 +438,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
var templ_7745c5c3_Var24 templ.SafeURL
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + book + "/" + c.ID + "/delete"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 142, Col: 96}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 144, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil {
@@ -467,7 +469,7 @@ func ContactsList(username, book string, contacts []ContactSummary) templ.Compon
})
}
// typeSelect renders the TYPE dropdown shared by email/address rows.
// typeSelect renders the TYPE dropdown shared by phone/email/address rows.
func typeSelect(name, selected string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
@@ -496,7 +498,7 @@ func typeSelect(name, selected string) templ.Component {
var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 161, Col: 20}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 163, Col: 20}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
if templ_7745c5c3_Err != nil {
@@ -512,7 +514,7 @@ func typeSelect(name, selected string) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ">Other</option> <option value=\"home\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ">Sonstige</option> <option value=\"home\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -522,7 +524,7 @@ func typeSelect(name, selected string) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, ">Home</option> <option value=\"work\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, ">Privat</option> <option value=\"work\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -532,82 +534,7 @@ func typeSelect(name, selected string) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, ">Work</option></select>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
// phoneTypeSelect renders the phone TYPE dropdown. An unspecified number is
// shown as "Mobile" (the vCard "cell" type), matching how mobile clients
// label a contact's main number.
func phoneTypeSelect(name, selected string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var27 := templ.GetChildren(ctx)
if templ_7745c5c3_Var27 == nil {
templ_7745c5c3_Var27 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "<select name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 172, Col: 20}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm\"><option value=\"cell\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if selected == "cell" || selected == "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, " selected")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, ">Mobile</option> <option value=\"home\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if selected == "home" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, " selected")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, ">Home</option> <option value=\"work\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if selected == "work" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, " selected")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, ">Work</option></select>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, ">Geschäftlich</option></select>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -631,33 +558,33 @@ func phoneRow(p LabeledValue) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var29 := templ.GetChildren(ctx)
if templ_7745c5c3_Var29 == nil {
templ_7745c5c3_Var29 = templ.NopComponent
templ_7745c5c3_Var27 := templ.GetChildren(ctx)
if templ_7745c5c3_Var27 == nil {
templ_7745c5c3_Var27 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "<div class=\"form-row flex gap-2 items-center\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "<div class=\"form-row flex gap-2 items-center\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = phoneTypeSelect("phone_type", p.Type).Render(ctx, templ_7745c5c3_Buffer)
templ_7745c5c3_Err = typeSelect("phone_type", p.Type).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "<input name=\"phone_value\" type=\"tel\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<input name=\"phone_value\" type=\"tel\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(p.Value)
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(p.Value)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 182, Col: 54}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 173, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" placeholder=\"Phone number\" class=\"flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs shrink-0\">Remove</button></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" placeholder=\"Telefonnummer\" class=\"flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs shrink-0\">Entfernen</button></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -681,12 +608,12 @@ func emailRow(p LabeledValue) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var31 := templ.GetChildren(ctx)
if templ_7745c5c3_Var31 == nil {
templ_7745c5c3_Var31 = templ.NopComponent
templ_7745c5c3_Var29 := templ.GetChildren(ctx)
if templ_7745c5c3_Var29 == nil {
templ_7745c5c3_Var29 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<div class=\"form-row flex gap-2 items-center\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<div class=\"form-row flex gap-2 items-center\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -694,20 +621,20 @@ func emailRow(p LabeledValue) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "<input name=\"email_value\" type=\"email\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<input name=\"email_value\" type=\"email\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(p.Value)
var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(p.Value)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 191, Col: 56}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 182, Col: 56}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" placeholder=\"Email address\" class=\"flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs shrink-0\">Remove</button></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" placeholder=\"E-Mail-Adresse\" class=\"flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs shrink-0\">Entfernen</button></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -731,12 +658,12 @@ func addressRow(a AddressValue) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var33 := templ.GetChildren(ctx)
if templ_7745c5c3_Var33 == nil {
templ_7745c5c3_Var33 = templ.NopComponent
templ_7745c5c3_Var31 := templ.GetChildren(ctx)
if templ_7745c5c3_Var31 == nil {
templ_7745c5c3_Var31 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<div class=\"form-row flex gap-2 items-center\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "<div class=\"form-row grid grid-cols-2 gap-2 items-start bg-gray-50 rounded-md p-3\"><div class=\"col-span-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -744,20 +671,72 @@ func addressRow(a AddressValue) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<input name=\"address_value\" type=\"text\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</div><input name=\"address_street\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.Street)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 193, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" placeholder=\"Straße und Hausnummer\" class=\"col-span-2 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <input name=\"address_city\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.City)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 195, Col: 55}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var33)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" placeholder=\"Stadt\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <input name=\"address_postal_code\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.Value)
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.PostalCode)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 200, Col: 57}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 197, Col: 68}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" placeholder=\"Street, city, postal code, country\" class=\"flex-1 rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs shrink-0\">Remove</button></div>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" placeholder=\"PLZ\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <input name=\"address_region\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.Region)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 199, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var35)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" placeholder=\"Bundesland/Region\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <input name=\"address_country\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.ResolveAttributeValue(a.Country)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 201, Col: 61}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" placeholder=\"Land\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm\"> <button type=\"button\" class=\"remove-row-btn text-red-600 hover:underline text-xs col-span-2 text-left\">Entfernen</button></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -781,12 +760,12 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var35 := templ.GetChildren(ctx)
if templ_7745c5c3_Var35 == nil {
templ_7745c5c3_Var35 = templ.NopComponent
templ_7745c5c3_Var37 := templ.GetChildren(ctx)
if templ_7745c5c3_Var37 == nil {
templ_7745c5c3_Var37 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var36 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_Var38 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -798,84 +777,84 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "<a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var37 templ.SafeURL
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + data.Book))
var templ_7745c5c3_Var39 templ.SafeURL
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + data.Book))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 208, Col: 51}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "\" class=\"text-sm text-indigo-600 hover:underline\">&larr; ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(data.Book)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 208, Col: 120}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</a><h1 class=\"text-2xl font-semibold mt-2 mb-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.ID == "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "New contact")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "Edit contact")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</h1>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if errMsg != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<p class=\"mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(errMsg)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 217, Col: 98}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 209, Col: 51}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</p>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" class=\"text-sm text-indigo-600 hover:underline\">&larr; ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, " <form method=\"POST\" action=\"")
var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(data.Book)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var40 templ.SafeURL
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinURLErrs(contactFormAction(data))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 221, Col: 35}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 209, Col: 120}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" enctype=\"multipart/form-data\" class=\"bg-white rounded-lg border border-gray-200 p-6 space-y-6 max-w-xl\"><div class=\"flex items-center gap-4\"><span id=\"current-avatar\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "</a><h1 class=\"text-2xl font-semibold mt-2 mb-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.ID == "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "New contact")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "Edit contact")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "</h1>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if errMsg != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<p class=\"mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(errMsg)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 218, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, " <form method=\"POST\" action=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var42 templ.SafeURL
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinURLErrs(contactFormAction(data))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 222, Col: 35}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "\" enctype=\"multipart/form-data\" class=\"bg-white rounded-lg border border-gray-200 p-6 space-y-6 max-w-xl\"><div class=\"flex items-center gap-4\"><span id=\"current-avatar\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -883,69 +862,56 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "</span> <img id=\"photo-preview\" src=\"\" alt=\"\" class=\"w-20 h-20 rounded-full object-cover hidden\"><div class=\"space-y-1\"><label class=\"cursor-pointer inline-block bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50\">Choose photo <input id=\"photo-input\" name=\"photo\" type=\"file\" accept=\"image/*\" class=\"hidden\"></label> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "</span> <img id=\"photo-preview\" src=\"\" alt=\"\" class=\"w-20 h-20 rounded-full object-cover hidden\"><div class=\"space-y-1\"><label class=\"cursor-pointer inline-block bg-white border border-gray-300 rounded-md px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50\">Foto wählen <input id=\"photo-input\" name=\"photo\" type=\"file\" accept=\"image/*\" class=\"hidden\"></label> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if data.PhotoDataURL != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "<label class=\"flex items-center gap-1 text-xs text-gray-500\"><input id=\"remove-photo\" name=\"remove_photo\" type=\"checkbox\" value=\"1\"> Remove photo</label>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "<label class=\"flex items-center gap-1 text-xs text-gray-500\"><input id=\"remove-photo\" name=\"remove_photo\" type=\"checkbox\" value=\"1\"> Foto entfernen</label>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "</div></div><div class=\"grid grid-cols-1 sm:grid-cols-2 gap-3\"><div><label class=\"block text-sm font-medium text-gray-700\">First name</label> <input name=\"forename\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Forename)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 247, Col: 61}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var41)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700\">Last name</label> <input name=\"surname\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var42 string
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Surname)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 252, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div></div><div><label class=\"block text-sm font-medium text-gray-700\">Organization</label> <input name=\"organization\" type=\"text\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</div></div><div><label class=\"block text-sm font-medium text-gray-700\">Full name</label> <input name=\"full_name\" type=\"text\" required value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var43 string
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Organization)
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.FullName)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 258, Col: 68}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 247, Col: 70}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var43)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700\">Birthday</label> <input name=\"birthday\" type=\"date\" value=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700\">Organization</label> <input name=\"organization\" type=\"text\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var44 string
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Birthday)
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Organization)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 263, Col: 60}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 252, Col: 68}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var44)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">Phones</label><div id=\"phones-container\" class=\"space-y-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700\">Geburtstag</label> <input name=\"birthday\" type=\"date\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.ResolveAttributeValue(data.Birthday)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 257, Col: 60}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var45)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\"></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">Telefonnummern</label><div id=\"phones-container\" class=\"space-y-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -955,7 +921,7 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "</div><button type=\"button\" data-add-target=\"phones-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ Add phone number</button></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">Emails</label><div id=\"emails-container\" class=\"space-y-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "</div><button type=\"button\" data-add-target=\"phones-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ Telefonnummer hinzufügen</button></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">E-Mail-Adressen</label><div id=\"emails-container\" class=\"space-y-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -965,7 +931,7 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "</div><button type=\"button\" data-add-target=\"emails-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ Add email address</button></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">Addresses</label><div id=\"addresses-container\" class=\"space-y-2\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "</div><button type=\"button\" data-add-target=\"emails-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ E-Mail-Adresse hinzufügen</button></div><div><label class=\"block text-sm font-medium text-gray-700 mb-2\">Adressen</label><div id=\"addresses-container\" class=\"space-y-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -975,39 +941,39 @@ func ContactForm(username string, data ContactFormData, errMsg string) templ.Com
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 74, "</div><button type=\"button\" data-add-target=\"addresses-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ Add address</button></div><div><label class=\"block text-sm font-medium text-gray-700\">Note</label> <textarea name=\"note\" rows=\"3\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "</div><button type=\"button\" data-add-target=\"addresses-container\" class=\"add-row-btn mt-2 text-sm text-indigo-600 hover:underline\">+ Adresse hinzufügen</button></div><div><label class=\"block text-sm font-medium text-gray-700\">Note</label> <textarea name=\"note\" rows=\"3\" class=\"mt-1 block w-full rounded-md border-gray-300 border px-3 py-2 shadow-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(data.Note)
var templ_7745c5c3_Var46 string
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(data.Note)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 306, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 75, "</textarea></div><div class=\"flex gap-2\"><button type=\"submit\" class=\"bg-indigo-600 text-white rounded-md px-4 py-2 text-sm font-medium hover:bg-indigo-700\">Save</button> <a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var46 templ.SafeURL
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + data.Book))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 312, Col: 53}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 300, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 76, "\" class=\"rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50\">Cancel</a></div></form><script type=\"module\" src=\"/web/static/contacts.js\"></script>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "</textarea></div><div class=\"flex gap-2\"><button type=\"submit\" class=\"bg-indigo-600 text-white rounded-md px-4 py-2 text-sm font-medium hover:bg-indigo-700\">Save</button> <a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var47 templ.SafeURL
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/contacts/" + data.Book))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/contacts.templ`, Line: 306, Col: 53}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "\" class=\"rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50\">Cancel</a></div></form><script type=\"module\" src=\"/web/static/contacts.js\"></script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
templ_7745c5c3_Err = Layout("Contacts", username).Render(templ.WithChildren(ctx, templ_7745c5c3_Var36), templ_7745c5c3_Buffer)
templ_7745c5c3_Err = Layout("Contacts", username).Render(templ.WithChildren(ctx, templ_7745c5c3_Var38), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+4 -29
View File
@@ -16,7 +16,7 @@ type FileEntry struct {
RelPath string // relative path (no leading slash) used to build the link
}
templ FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, currentPath string, sortBy string, sortDir string) {
templ FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, currentPath string) {
@Layout("Files", username) {
<div class="flex items-center justify-between mb-6 gap-4 flex-wrap">
<h1 class="text-2xl font-semibold">Files</h1>
@@ -33,10 +33,6 @@ templ FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry,
Upload folder
<input id="upload-folder-input" type="file" webkitdirectory multiple class="hidden"/>
</label>
<select id="sort-select" class="rounded-md border-gray-300 border px-2 py-1.5 text-sm text-gray-700">
<option value="name_asc" selected?={ sortBy == "name" && sortDir == "asc" }>Name (asc)</option>
<option value="name_desc" selected?={ sortBy == "name" && sortDir == "desc" }>Name (desc)</option>
</select>
</div>
</div>
@@ -52,8 +48,6 @@ templ FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry,
id="file-drop-zone"
data-current-path={ currentPath }
data-upload-url={ "/web/files/" + currentPath }
data-sort-by={ sortBy }
data-sort-dir={ sortDir }
class="bg-white rounded-lg border-2 border-dashed border-gray-200 p-2 transition-colors"
>
<!-- Table layout for wider screens (sm and up). -->
@@ -66,29 +60,9 @@ templ FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry,
</colgroup>
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100">
<th class="py-2 px-3 font-medium">
if sortBy == "name" {
if sortDir == "asc" {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=desc") } class="hover:text-indigo-600">Name <span class="ml-1 text-xs"></span></a>
} else {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=asc") } class="hover:text-indigo-600">Name <span class="ml-1 text-xs"></span></a>
}
} else {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=asc") } class="hover:text-indigo-600">Name</a>
}
</th>
<th class="py-2 px-3 font-medium">Name</th>
<th class="py-2 px-3 font-medium">Size</th>
<th class="py-2 px-3 font-medium">
if sortBy == "modtime" {
if sortDir == "asc" {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=desc") } class="hover:text-indigo-600">Modified <span class="ml-1 text-xs"></span></a>
} else {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=asc") } class="hover:text-indigo-600">Modified <span class="ml-1 text-xs"></span></a>
}
} else {
<a href={ templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=asc") } class="hover:text-indigo-600">Modified</a>
}
</th>
<th class="py-2 px-3 font-medium">Modified</th>
<th class="py-2 px-3 font-medium"></th>
</tr>
</thead>
@@ -189,3 +163,4 @@ templ fileDeleteButton(e FileEntry) {
Delete
</button>
}
+128 -296
View File
@@ -24,7 +24,7 @@ type FileEntry struct {
RelPath string // relative path (no leading slash) used to build the link
}
func FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, currentPath string, sortBy string, sortDir string) templ.Component {
func FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, currentPath string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
@@ -57,276 +57,176 @@ func FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, c
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"flex items-center justify-between mb-6 gap-4 flex-wrap\"><h1 class=\"text-2xl font-semibold\">Files</h1><div class=\"flex gap-2 flex-wrap\"><button id=\"new-folder-button\" type=\"button\" 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\">New folder</button> <label class=\"cursor-pointer bg-indigo-600 text-white rounded-md px-3 py-1.5 text-sm font-medium hover:bg-indigo-700\">Upload files <input id=\"upload-files-input\" type=\"file\" multiple class=\"hidden\"></label> <label class=\"cursor-pointer bg-indigo-600 text-white rounded-md px-3 py-1.5 text-sm font-medium hover:bg-indigo-700\">Upload folder <input id=\"upload-folder-input\" type=\"file\" webkitdirectory multiple class=\"hidden\"></label> <select id=\"sort-select\" class=\"rounded-md border-gray-300 border px-2 py-1.5 text-sm text-gray-700\"><option value=\"name_asc\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sortBy == "name" && sortDir == "asc" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, " selected")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, ">Name (asc)</option> <option value=\"name_desc\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sortBy == "name" && sortDir == "desc" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, " selected")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, ">Name (desc)</option></select></div></div><nav class=\"text-sm text-gray-500 mb-4 flex flex-wrap items-center gap-1\"><a href=\"/web/files/\" class=\"hover:underline text-indigo-600\">home</a> ")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"flex items-center justify-between mb-6 gap-4 flex-wrap\"><h1 class=\"text-2xl font-semibold\">Files</h1><div class=\"flex gap-2 flex-wrap\"><button id=\"new-folder-button\" type=\"button\" 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\">New folder</button> <label class=\"cursor-pointer bg-indigo-600 text-white rounded-md px-3 py-1.5 text-sm font-medium hover:bg-indigo-700\">Upload files <input id=\"upload-files-input\" type=\"file\" multiple class=\"hidden\"></label> <label class=\"cursor-pointer bg-indigo-600 text-white rounded-md px-3 py-1.5 text-sm font-medium hover:bg-indigo-700\">Upload folder <input id=\"upload-folder-input\" type=\"file\" webkitdirectory multiple class=\"hidden\"></label></div></div><nav class=\"text-sm text-gray-500 mb-4 flex flex-wrap items-center gap-1\"><a href=\"/web/files/\" class=\"hover:underline text-indigo-600\">home</a> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, bc := range breadcrumbs {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<span>/</span> <a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<span>/</span> <a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 templ.SafeURL
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + bc.Path + "/"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 47, Col: 54}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 43, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" class=\"hover:underline text-indigo-600\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\" class=\"hover:underline text-indigo-600\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(bc.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 47, Col: 106}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 43, Col: 106}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</nav><div id=\"file-drop-zone\" data-current-path=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</nav><div id=\"file-drop-zone\" data-current-path=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.ResolveAttributeValue(currentPath)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 53, Col: 34}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 49, Col: 34}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "\" data-upload-url=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\" data-upload-url=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue("/web/files/" + currentPath)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 54, Col: 48}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 50, Col: 48}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\" data-sort-by=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" class=\"bg-white rounded-lg border-2 border-dashed border-gray-200 p-2 transition-colors\"><!-- Table layout for wider screens (sm and up). --><table class=\"hidden sm:table w-full text-sm table-fixed\"><colgroup><col class=\"w-auto\"> <col class=\"w-20\"> <col class=\"w-36\"> <col class=\"w-16\"></colgroup> <thead><tr class=\"text-left text-gray-400 border-b border-gray-100\"><th class=\"py-2 px-3 font-medium\">Name</th><th class=\"py-2 px-3 font-medium\">Size</th><th class=\"py-2 px-3 font-medium\">Modified</th><th class=\"py-2 px-3 font-medium\"></th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, e := range entries {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<tr class=\"border-b border-gray-50 hover:bg-gray-50\"><td class=\"py-2 px-3 break-all\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = fileEntryLink(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</td><td class=\"py-2 px-3 text-gray-500 whitespace-nowrap\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.ResolveAttributeValue(sortBy)
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(e.Size)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 55, Col: 24}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 75, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "\" data-sort-dir=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</td><td class=\"py-2 px-3 text-gray-500 whitespace-nowrap\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.ResolveAttributeValue(sortDir)
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(e.ModTime)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 56, Col: 26}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 76, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\" class=\"bg-white rounded-lg border-2 border-dashed border-gray-200 p-2 transition-colors\"><!-- Table layout for wider screens (sm and up). --><table class=\"hidden sm:table w-full text-sm table-fixed\"><colgroup><col class=\"w-auto\"> <col class=\"w-20\"> <col class=\"w-36\"> <col class=\"w-16\"></colgroup> <thead><tr class=\"text-left text-gray-400 border-b border-gray-100\"><th class=\"py-2 px-3 font-medium\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</td><td class=\"py-2 px-3 text-right whitespace-nowrap\"><div class=\"flex items-center justify-end gap-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sortBy == "name" {
if sortDir == "asc" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<a href=\"")
templ_7745c5c3_Err = fileActions(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 templ.SafeURL
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=desc"))
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</div></td></tr>")
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 72, Col: 89}
return templ_7745c5c3_Err
}
}
if len(entries) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<tr><td colspan=\"4\" class=\"py-6 px-3 text-center text-gray-400\">This folder is empty — drag &amp; drop files or folders here, or use the upload buttons above.</td></tr>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</tbody></table><!-- Stacked card layout for narrow screens: same information as\n\t\t\t the table above (name, size, modified, delete), just\n\t\t\t wrapped onto its own lines instead of squeezed into\n\t\t\t columns, so nothing needs to be hidden or scrolled to. --><ul class=\"sm:hidden divide-y divide-gray-100\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, e := range entries {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<li class=\"py-2.5 px-1\"><div class=\"break-all\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = fileEntryLink(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div><div class=\"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 pl-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if e.Size != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "<span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(e.Size)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 106, Col: 22}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "\" class=\"hover:text-indigo-600\">Name <span class=\"ml-1 text-xs\">↓</span></a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<a href=\"")
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 templ.SafeURL
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=asc"))
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(e.ModTime)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 74, Col: 88}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 108, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\" class=\"hover:text-indigo-600\">Name <span class=\"ml-1 text-xs\">↑</span></a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 templ.SafeURL
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=name&sort_dir=asc"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 77, Col: 87}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "\" class=\"hover:text-indigo-600\">Name</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</th><th class=\"py-2 px-3 font-medium\">Size</th><th class=\"py-2 px-3 font-medium\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if sortBy == "modtime" {
if sortDir == "asc" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 templ.SafeURL
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=desc"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 84, Col: 92}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "\" class=\"hover:text-indigo-600\">Modified <span class=\"ml-1 text-xs\">↓</span></a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 templ.SafeURL
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=asc"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 86, Col: 91}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\" class=\"hover:text-indigo-600\">Modified <span class=\"ml-1 text-xs\">↑</span></a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 templ.SafeURL
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + currentPath + "?sort_by=modtime&sort_dir=asc"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 89, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "\" class=\"hover:text-indigo-600\">Modified</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</th><th class=\"py-2 px-3 font-medium\"></th></tr></thead> <tbody>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, e := range entries {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<tr class=\"border-b border-gray-50 hover:bg-gray-50\"><td class=\"py-2 px-3 break-all\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = fileEntryLink(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</td><td class=\"py-2 px-3 text-gray-500 whitespace-nowrap\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(e.Size)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 101, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</td><td class=\"py-2 px-3 text-gray-500 whitespace-nowrap\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(e.ModTime)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 102, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</td><td class=\"py-2 px-3 text-right whitespace-nowrap\"><div class=\"flex items-center justify-end gap-3\">")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</span> <span class=\"ml-auto flex items-center gap-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -334,86 +234,18 @@ func FilesPage(username string, breadcrumbs []Breadcrumb, entries []FileEntry, c
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</div></td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</span></div></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(entries) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<tr><td colspan=\"4\" class=\"py-6 px-3 text-center text-gray-400\">This folder is empty — drag &amp; drop files or folders here, or use the upload buttons above.</td></tr>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "<li class=\"py-6 px-3 text-center text-gray-400 text-sm\">This folder is empty — drag &amp; drop files or folders here, or use the upload buttons above.</li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "</tbody></table><!-- Stacked card layout for narrow screens: same information as\n\t\t\t the table above (name, size, modified, delete), just\n\t\t\t wrapped onto its own lines instead of squeezed into\n\t\t\t columns, so nothing needs to be hidden or scrolled to. --><ul class=\"sm:hidden divide-y divide-gray-100\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, e := range entries {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<li class=\"py-2.5 px-1\"><div class=\"break-all\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = fileEntryLink(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</div><div class=\"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 pl-6\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if e.Size != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "<span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(e.Size)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 132, Col: 22}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(e.ModTime)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 134, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "</span> <span class=\"ml-auto flex items-center gap-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = fileActions(e).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "</span></div></li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if len(entries) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "<li class=\"py-6 px-3 text-center text-gray-400 text-sm\">This folder is empty — drag &amp; drop files or folders here, or use the upload buttons above.</li>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</ul></div><p id=\"upload-status\" class=\"mt-3 text-sm text-gray-500\"></p><script type=\"module\" src=\"/web/static/files.js\"></script>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</ul></div><p id=\"upload-status\" class=\"mt-3 text-sm text-gray-500\"></p><script type=\"module\" src=\"/web/static/files.js\"></script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -443,70 +275,70 @@ func fileEntryLink(e FileEntry) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var19 := templ.GetChildren(ctx)
if templ_7745c5c3_Var19 == nil {
templ_7745c5c3_Var19 = templ.NopComponent
templ_7745c5c3_Var11 := templ.GetChildren(ctx)
if templ_7745c5c3_Var11 == nil {
templ_7745c5c3_Var11 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if e.IsDir {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "<a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 templ.SafeURL
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath + "/"))
var templ_7745c5c3_Var12 templ.SafeURL
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath + "/"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 155, Col: 54}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 129, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" class=\"flex items-center gap-2 text-indigo-600 hover:underline\"><span aria-hidden=\"true\">📁</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "\" class=\"flex items-center gap-2 text-indigo-600 hover:underline\"><span aria-hidden=\"true\">📁</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(e.Name)
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(e.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 156, Col: 47}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 130, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "</a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "<a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var22 templ.SafeURL
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath))
var templ_7745c5c3_Var14 templ.SafeURL
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 159, Col: 48}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 133, Col: 48}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" target=\"_blank\" rel=\"noopener\" class=\"flex items-center gap-2 text-gray-700 hover:underline\"><span aria-hidden=\"true\">📄</span>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "\" target=\"_blank\" rel=\"noopener\" class=\"flex items-center gap-2 text-gray-700 hover:underline\"><span aria-hidden=\"true\">📄</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(e.Name)
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(e.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 160, Col: 47}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 134, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "</a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -536,26 +368,26 @@ func fileActions(e FileEntry) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var24 := templ.GetChildren(ctx)
if templ_7745c5c3_Var24 == nil {
templ_7745c5c3_Var24 = templ.NopComponent
templ_7745c5c3_Var16 := templ.GetChildren(ctx)
if templ_7745c5c3_Var16 == nil {
templ_7745c5c3_Var16 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
if !e.IsDir {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "<a href=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "<a href=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var25 templ.SafeURL
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath + "?download=1"))
var templ_7745c5c3_Var17 templ.SafeURL
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinURLErrs(templ.URL("/web/files/" + e.RelPath + "?download=1"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 173, Col: 62}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 147, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" class=\"text-gray-500 hover:text-indigo-600 hover:underline text-xs font-medium\">Download</a>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" class=\"text-gray-500 hover:text-indigo-600 hover:underline text-xs font-medium\">Download</a>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -584,38 +416,38 @@ func fileDeleteButton(e FileEntry) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var26 := templ.GetChildren(ctx)
if templ_7745c5c3_Var26 == nil {
templ_7745c5c3_Var26 = templ.NopComponent
templ_7745c5c3_Var18 := templ.GetChildren(ctx)
if templ_7745c5c3_Var18 == nil {
templ_7745c5c3_Var18 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "<button type=\"button\" class=\"delete-entry-button text-red-500 hover:text-red-700 text-xs font-medium\" data-path=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<button type=\"button\" class=\"delete-entry-button text-red-500 hover:text-red-700 text-xs font-medium\" data-path=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(e.RelPath)
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.ResolveAttributeValue(e.RelPath)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 186, Col: 23}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 160, Col: 23}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var19)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\" data-name=\"")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(e.Name)
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.ResolveAttributeValue(e.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 187, Col: 20}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/templates/files.templ`, Line: 161, Col: 20}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\">Delete</button>")
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\">Delete</button>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+3 -3
View File
@@ -7,14 +7,14 @@ import (
"path/filepath"
"sync"
"git.arnef.de/arnef/nidus/internal/auth"
"git.arnef.de/arnef/nidus/internal/config"
"github.com/yourusername/caldav-server/internal/auth"
"github.com/yourusername/caldav-server/internal/config"
xwebdav "golang.org/x/net/webdav"
)
// NewHandler returns an http.Handler that provides standard WebDAV file access,
// mounted at the fixed URL /files/ for every user and rooted at
// dataDir/<username>/files on disk. The URL is the same for all users —
// dataDir/<username>/files/ on disk. The URL is the same for all users —
// which user's directory is served is resolved from the Basic Auth identity
// in the request context, not from the URL.
//
+4 -4
View File
@@ -9,8 +9,8 @@ import (
"strings"
"testing"
"git.arnef.de/arnef/nidus/internal/auth"
filewebdav "git.arnef.de/arnef/nidus/internal/webdav"
"github.com/yourusername/caldav-server/internal/auth"
filewebdav "github.com/yourusername/caldav-server/internal/webdav"
)
func testLogger() *slog.Logger {
@@ -54,8 +54,8 @@ func TestPerUserIsolationAndPrefix(t *testing.T) {
t.Fatalf("expected bob to get 404 for alice's file, got %d", bobRec.Code)
}
// Confirm the file physically landed under dataDir/alice/files/, not
// nested under an extra files/files/... path.
// Confirm the file physically landed under dataDir/alice/files/, matching
// the new nested structure.
if _, err := os.Stat(dir + "/alice/files/note.txt"); err != nil {
t.Fatalf("expected file at dataDir/alice/files/note.txt: %v", err)
}
-62
View File
@@ -1,62 +0,0 @@
// Command migrate is a tool to restructure the data directory from the
// old format to the new unified format.
package main
import (
"flag"
"fmt"
"log/slog"
"os"
"git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/store"
)
func main() {
os.Exit(run(os.Args[1:]))
}
func run(args []string) int {
fs := flag.NewFlagSet("migrate", flag.ContinueOnError)
verbose := fs.Bool("verbose", false, "enable verbose output")
if err := fs.Parse(args); err != nil {
return 2
}
cfg, err := config.Load()
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
return 1
}
logger := buildLogger(*verbose)
st, err := store.NewStore(cfg.Storage.DataDir)
if err != nil {
fmt.Fprintf(os.Stderr, "error opening store %q: %v\n", cfg.Storage.DataDir, err)
return 1
}
logger.Info("starting migration", "data_dir", cfg.Storage.DataDir)
if err := st.Migrate(); err != nil {
logger.Error("migration failed", "error", err)
fmt.Fprintf(os.Stderr, "migration failed: %v\n", err)
return 1
}
logger.Info("migration completed successfully")
fmt.Println("Migration completed successfully")
return 0
}
func buildLogger(verbose bool) *slog.Logger {
level := slog.LevelInfo
if verbose {
level = slog.LevelDebug
}
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: level,
})
return slog.New(handler)
}
+48 -54
View File
@@ -8,13 +8,14 @@
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"git.arnef.de/arnef/nidus/internal/config"
"git.arnef.de/arnef/nidus/internal/db"
"git.arnef.de/arnef/nidus/internal/store"
"github.com/yourusername/caldav-server/internal/config"
"github.com/yourusername/caldav-server/internal/db"
"github.com/yourusername/caldav-server/internal/store"
)
func main() {
@@ -22,12 +23,18 @@ func main() {
}
func run(args []string) int {
if len(args) < 1 {
fs := flag.NewFlagSet("nidusctl", flag.ContinueOnError)
cfgPath := fs.String("config", "config.yaml", "path to configuration file")
if err := fs.Parse(args); err != nil {
return 2
}
rest := fs.Args()
if len(rest) < 1 {
usage()
return 2
}
cfg, err := config.Load()
cfg, err := config.Load(*cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
return 1
@@ -47,20 +54,18 @@ func run(args []string) int {
return 1
}
switch args[0] {
switch rest[0] {
case "user":
return runUser(dbase, args[1:])
return runUser(dbase, rest[1:])
case "calendar", "cal":
return runCalendar(dbase, st, args[1:])
return runCalendar(dbase, st, rest[1:])
case "addressbook", "card":
return runAddressBook(dbase, st, args[1:])
case "migrate":
return runMigrate(st, args[1:])
return runAddressBook(dbase, st, rest[1:])
case "help", "-h", "--help":
usage()
return 0
default:
fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
fmt.Fprintf(os.Stderr, "unknown command %q\n\n", rest[0])
usage()
return 2
}
@@ -70,32 +75,25 @@ func usage() {
fmt.Fprint(os.Stderr, `nidusctl - manage nidus DAV server users, resources, and sharing grants
Usage:
nidusctl user create <username> [--display-name NAME] [--email EMAIL] [--password PW]
nidusctl user delete <username>
nidusctl user list
nidusctl user passwd <username> [--password PW]
nidusctl [-config config.yaml] user create <username> [--display-name NAME] [--email EMAIL] [--password PW]
nidusctl [-config config.yaml] user delete <username>
nidusctl [-config config.yaml] user list
nidusctl [-config config.yaml] user passwd <username> [--password PW]
nidusctl calendar create <owner> <calendar> [--color '#RRGGBB']
nidusctl calendar color <owner> <calendar> <hex-color>
nidusctl calendar delete <owner> <calendar>
nidusctl calendar list <owner>
nidusctl calendar share <owner> <calendar> <user> <read|write>
nidusctl calendar unshare <owner> <calendar> <user>
nidusctl calendar shares <owner> <calendar>
nidusctl [-config config.yaml] calendar create <owner> <calendar> [--color '#RRGGBB']
nidusctl [-config config.yaml] calendar color <owner> <calendar> <hex-color>
nidusctl [-config config.yaml] calendar delete <owner> <calendar>
nidusctl [-config config.yaml] calendar list <owner>
nidusctl [-config config.yaml] calendar share <owner> <calendar> <user> <read|write>
nidusctl [-config config.yaml] calendar unshare <owner> <calendar> <user>
nidusctl [-config config.yaml] calendar shares <owner> <calendar>
nidusctl addressbook create <owner> <book>
nidusctl addressbook delete <owner> <book>
nidusctl addressbook list <owner>
nidusctl addressbook share <owner> <book> <user> <read|write>
nidusctl addressbook unshare <owner> <book> <user>
nidusctl addressbook shares <owner> <book>
nidusctl migrate [--verbose]
nidusctl help
Configuration is done via environment variables:
NIDUS_DATA_DIR - data directory (default: ./data)
nidusctl [-config config.yaml] addressbook create <owner> <book>
nidusctl [-config config.yaml] addressbook delete <owner> <book>
nidusctl [-config config.yaml] addressbook list <owner>
nidusctl [-config config.yaml] addressbook share <owner> <book> <user> <read|write>
nidusctl [-config config.yaml] addressbook unshare <owner> <book> <user>
nidusctl [-config config.yaml] addressbook shares <owner> <book>
Examples:
nidusctl user create alice --display-name "Alice Smith" --email alice@example.com
@@ -103,10 +101,16 @@ Examples:
nidusctl calendar share alice work bob write
nidusctl calendar shares alice work
nidusctl calendar unshare alice work bob
nidusctl migrate
`)
}
// newFlagSet creates a flag.FlagSet configured for subcommand parsing
// (flags may appear before or after positional args, since callers parse
// flags first with fs.Parse then read fs.Args() for the rest).
func newFlagSet(name string) *flag.FlagSet {
return flag.NewFlagSet(name, flag.ContinueOnError)
}
func runCalendar(dbase *db.DB, st *store.Store, args []string) int {
if len(args) < 1 {
usage()
@@ -114,17 +118,17 @@ func runCalendar(dbase *db.DB, st *store.Store, args []string) int {
}
switch args[0] {
case "create":
color := ""
if len(args) > 2 && args[1] == "--color" {
color = args[2]
args = args[:1]
fs := newFlagSet("calendar create")
color := fs.String("color", "", "hex color like #3b82f6 (optional)")
if err := fs.Parse(args[1:]); err != nil {
return 2
}
if len(args) != 3 {
if fs.NArg() != 2 {
fmt.Fprintln(os.Stderr, "usage: nidusctl calendar create <owner> <calendar> [--color '#RRGGBB']")
return 2
}
owner, calName := args[1], args[2]
if err := dbase.CreateCalendarWithColor(owner, calName, color); err != nil {
owner, calName := fs.Arg(0), fs.Arg(1)
if err := dbase.CreateCalendarWithColor(owner, calName, *color); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return 1
}
@@ -355,16 +359,6 @@ func runAddressBook(dbase *db.DB, st *store.Store, args []string) int {
}
}
func runMigrate(st *store.Store, args []string) int {
// Ignore args for now (could add --verbose flag in future if needed)
if err := st.Migrate(); err != nil {
fmt.Fprintf(os.Stderr, "migration failed: %v\n", err)
return 1
}
fmt.Println("Migration completed successfully")
return 0
}
// warnIfUnknownUser reports (without failing) if username is not a
// registered user — the share is still recorded, since a user could be
// created afterwards.
+39 -19
View File
@@ -9,9 +9,28 @@ import (
"strings"
"testing"
"git.arnef.de/arnef/nidus/internal/db"
"github.com/yourusername/caldav-server/internal/db"
)
// writeTestConfig creates a minimal config.yaml in dir and returns its path.
func writeTestConfig(t *testing.T, dir string) string {
t.Helper()
cfgPath := filepath.Join(dir, "config.yaml")
dataDir := filepath.Join(dir, "data")
content := "storage:\n data_dir: " + dataDir + "\n" +
"users:\n" +
" alice:\n" +
" password: \"$2a$10$9.WEs0uz5TaNJLQbSTLrX.Te.BIe8XTTykVRzZbSHQMEkyFb8Sq/O\"\n" +
" bob:\n" +
" password: \"$2a$10$9.WEs0uz5TaNJLQbSTLrX.Te.BIe8XTTykVRzZbSHQMEkyFb8Sq/O\"\n"
if err := os.WriteFile(cfgPath, []byte(content), 0o644); err != nil {
t.Fatalf("writing test config: %v", err)
}
return cfgPath
}
// runCLI runs the CLI's run() function, capturing stdout/stderr, and
// returns (exit code, combined stdout+stderr).
func runCLI(t *testing.T, args ...string) (int, string) {
t.Helper()
@@ -37,9 +56,9 @@ func runCLI(t *testing.T, args ...string) (int, string) {
func TestCalendarShareUnshareLifecycle(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "calendar", "share", "alice", "work", "bob", "write")
code, out := runCLI(t, "-config", cfgPath, "calendar", "share", "alice", "work", "bob", "write")
if code != 0 {
t.Fatalf("share exit code = %d, output: %s", code, out)
}
@@ -47,7 +66,7 @@ func TestCalendarShareUnshareLifecycle(t *testing.T) {
t.Errorf("output = %q, want to contain 'shared'", out)
}
code, out = runCLI(t, "calendar", "shares", "alice", "work")
code, out = runCLI(t, "-config", cfgPath, "calendar", "shares", "alice", "work")
if code != 0 {
t.Fatalf("shares exit code = %d, output: %s", code, out)
}
@@ -55,12 +74,12 @@ func TestCalendarShareUnshareLifecycle(t *testing.T) {
t.Errorf("output = %q, want to contain bob/write", out)
}
code, out = runCLI(t, "calendar", "unshare", "alice", "work", "bob")
code, out = runCLI(t, "-config", cfgPath, "calendar", "unshare", "alice", "work", "bob")
if code != 0 {
t.Fatalf("unshare exit code = %d, output: %s", code, out)
}
code, out = runCLI(t, "calendar", "shares", "alice", "work")
code, out = runCLI(t, "-config", cfgPath, "calendar", "shares", "alice", "work")
if code != 0 {
t.Fatalf("shares (after unshare) exit code = %d, output: %s", code, out)
}
@@ -71,9 +90,9 @@ func TestCalendarShareUnshareLifecycle(t *testing.T) {
func TestCalendarShareInvalidPermission(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "calendar", "share", "alice", "work", "bob", "admin")
code, out := runCLI(t, "-config", cfgPath, "calendar", "share", "alice", "work", "bob", "admin")
if code != 2 {
t.Errorf("exit code = %d, want 2; output: %s", code, out)
}
@@ -84,9 +103,9 @@ func TestCalendarShareInvalidPermission(t *testing.T) {
func TestCalendarUnshareNotFound(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "calendar", "unshare", "alice", "ghost", "bob")
code, out := runCLI(t, "-config", cfgPath, "calendar", "unshare", "alice", "ghost", "bob")
if code != 1 {
t.Errorf("exit code = %d, want 1; output: %s", code, out)
}
@@ -97,14 +116,14 @@ func TestCalendarUnshareNotFound(t *testing.T) {
func TestAddressBookShareUnshareLifecycle(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "addressbook", "share", "alice", "contacts", "bob", "read")
code, out := runCLI(t, "-config", cfgPath, "addressbook", "share", "alice", "contacts", "bob", "read")
if code != 0 {
t.Fatalf("share exit code = %d, output: %s", code, out)
}
code, out = runCLI(t, "addressbook", "shares", "alice", "contacts")
code, out = runCLI(t, "-config", cfgPath, "addressbook", "shares", "alice", "contacts")
if code != 0 {
t.Fatalf("shares exit code = %d, output: %s", code, out)
}
@@ -112,7 +131,7 @@ func TestAddressBookShareUnshareLifecycle(t *testing.T) {
t.Errorf("output = %q, want to contain bob/read", out)
}
code, out = runCLI(t, "addressbook", "unshare", "alice", "contacts", "bob")
code, out = runCLI(t, "-config", cfgPath, "addressbook", "unshare", "alice", "contacts", "bob")
if code != 0 {
t.Fatalf("unshare exit code = %d, output: %s", code, out)
}
@@ -120,9 +139,9 @@ func TestAddressBookShareUnshareLifecycle(t *testing.T) {
func TestUnknownUserWarningDoesNotBlockShare(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "calendar", "share", "alice", "work", "carol", "read")
code, out := runCLI(t, "-config", cfgPath, "calendar", "share", "alice", "work", "carol", "read")
if code != 0 {
t.Fatalf("exit code = %d, output: %s", code, out)
}
@@ -135,9 +154,10 @@ func TestUnknownUserWarningDoesNotBlockShare(t *testing.T) {
}
func TestNoArgsShowsUsage(t *testing.T) {
dir := t.TempDir()
// No config needed since usage() is printed before config.Load for
// missing subcommands.
code, out := runCLI(t)
code, out := runCLI(t, "-config", filepath.Join(dir, "missing.yaml"))
if code != 2 {
t.Errorf("exit code = %d, want 2", code)
}
@@ -148,9 +168,9 @@ func TestNoArgsShowsUsage(t *testing.T) {
func TestUnknownCommand(t *testing.T) {
dir := t.TempDir()
t.Setenv("NIDUS_DATA_DIR", filepath.Join(dir, "data"))
cfgPath := writeTestConfig(t, dir)
code, out := runCLI(t, "bogus")
code, out := runCLI(t, "-config", cfgPath, "bogus")
if code != 2 {
t.Errorf("exit code = %d, want 2", code)
}
+21 -45
View File
@@ -6,7 +6,7 @@ import (
"os"
"strings"
"git.arnef.de/arnef/nidus/internal/db"
"github.com/yourusername/caldav-server/internal/db"
"golang.org/x/term"
)
@@ -31,47 +31,31 @@ func runUser(dbase *db.DB, args []string) int {
}
func userCreate(dbase *db.DB, args []string) int {
var displayName, email, password string
var rest []string
for i := 0; i < len(args); i++ {
switch args[i] {
case "--display-name":
if i+1 < len(args) {
displayName = args[i+1]
i++
fs := newFlagSet("nidusctl user create")
displayName := fs.String("display-name", "", "display name shown in DAV clients")
email := fs.String("email", "", "email address")
password := fs.String("password", "", "password (omit to be prompted, recommended)")
if err := fs.Parse(args); err != nil {
return 2
}
case "--email":
if i+1 < len(args) {
email = args[i+1]
i++
}
case "--password":
if i+1 < len(args) {
password = args[i+1]
i++
}
default:
rest = append(rest, args[i])
}
}
rest := fs.Args()
if len(rest) != 1 {
fmt.Fprintln(os.Stderr, "usage: nidusctl user create <username> [--display-name NAME] [--email EMAIL] [--password PASSWORD]")
return 2
}
username := rest[0]
if password == "" {
pw := *password
if pw == "" {
var err error
password, err = promptPassword(username)
pw, err = promptPassword(username)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading password: %v\n", err)
return 1
}
}
if err := dbase.CreateUser(username, password, displayName, email); err != nil {
if err := dbase.CreateUser(username, pw, *displayName, *email); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return 1
}
@@ -114,37 +98,29 @@ func userList(dbase *db.DB, args []string) int {
}
func userPasswd(dbase *db.DB, args []string) int {
var password string
var rest []string
for i := 0; i < len(args); i++ {
switch args[i] {
case "--password":
if i+1 < len(args) {
password = args[i+1]
i++
fs := newFlagSet("nidusctl user passwd")
password := fs.String("password", "", "new password (omit to be prompted, recommended)")
if err := fs.Parse(args); err != nil {
return 2
}
default:
rest = append(rest, args[i])
}
}
rest := fs.Args()
if len(rest) != 1 {
fmt.Fprintln(os.Stderr, "usage: nidusctl user passwd <username> [--password PASSWORD]")
return 2
}
username := rest[0]
if password == "" {
pw := *password
if pw == "" {
var err error
password, err = promptPassword(username)
pw, err = promptPassword(username)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading password: %v\n", err)
return 1
}
}
if err := dbase.SetPassword(username, password); err != nil {
if err := dbase.SetPassword(username, pw); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return 1
}
+1 -1
View File
File diff suppressed because one or more lines are too long
+12 -18
View File
@@ -9,7 +9,6 @@
const filesInput = document.getElementById("upload-files-input");
const folderInput = document.getElementById("upload-folder-input");
const newFolderButton = document.getElementById("new-folder-button");
const sortSelect = document.getElementById("sort-select");
const status = document.getElementById("upload-status");
if (!dropZone) {
return;
@@ -26,6 +25,11 @@
}
const formData = new FormData();
for (const file of files) {
// A folder-selected/dropped file's relative path (e.g.
// "photos/2024/img.jpg") is sent as a parallel "paths" field
// (same order as "files") since the server strips any
// directory component from the file's own filename per the
// multipart spec — see internal/web/files.go.
const relPath = file.webkitRelativePath || file.name;
formData.append("files", file, file.name);
formData.append("paths", relPath);
@@ -52,7 +56,7 @@
void upload(Array.from(folderInput.files || []));
folderInput.value = "";
});
const folderNameRe = /^[a-zA-Z0-9._-]{1,64}$/;
const folderNameRe = /^[a-zA-Z0-9_-]{1,64}$/;
newFolderButton?.addEventListener("click", async () => {
const name = window.prompt("New folder name:");
if (!name) {
@@ -102,22 +106,10 @@
}
});
});
if (sortSelect) {
sortSelect.addEventListener("change", () => {
const value = sortSelect.value;
let sortBy = "name";
let sortDir = "asc";
if (value === "name_asc") {
sortBy = "name";
sortDir = "asc";
}
else if (value === "name_desc") {
sortBy = "name";
sortDir = "desc";
}
window.location.href = `${uploadUrl}?sort_by=${sortBy}&sort_dir=${sortDir}`;
});
}
// Recursively walk a dropped DataTransferItem (file or directory) into
// a flat list of File objects, using the browser's non-standard but
// widely-supported webkitGetAsEntry/FileSystemEntry APIs to support
// dragging & dropping whole folders.
function readEntry(entry) {
return new Promise((resolve) => {
if (entry.isFile) {
@@ -171,6 +163,8 @@
}
}
if (entries.length === 0) {
// Fallback for browsers without webkitGetAsEntry support: flat
// files only, no folder traversal.
void upload(Array.from(e.dataTransfer?.files || []));
return;
}
+12 -18
View File
@@ -8,7 +8,6 @@
const filesInput = document.getElementById("upload-files-input") as HTMLInputElement | null;
const folderInput = document.getElementById("upload-folder-input") as HTMLInputElement | null;
const newFolderButton = document.getElementById("new-folder-button") as HTMLButtonElement | null;
const sortSelect = document.getElementById("sort-select") as HTMLSelectElement | null;
const status = document.getElementById("upload-status") as HTMLParagraphElement | null;
if (!dropZone) {
return;
@@ -28,6 +27,11 @@
}
const formData = new FormData();
for (const file of files) {
// A folder-selected/dropped file's relative path (e.g.
// "photos/2024/img.jpg") is sent as a parallel "paths" field
// (same order as "files") since the server strips any
// directory component from the file's own filename per the
// multipart spec — see internal/web/files.go.
const relPath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
formData.append("files", file, file.name);
formData.append("paths", relPath);
@@ -57,7 +61,7 @@
folderInput.value = "";
});
const folderNameRe = /^[a-zA-Z0-9._-]{1,64}$/;
const folderNameRe = /^[a-zA-Z0-9_-]{1,64}$/;
newFolderButton?.addEventListener("click", async () => {
const name = window.prompt("New folder name:");
@@ -108,22 +112,10 @@
});
});
if (sortSelect) {
sortSelect.addEventListener("change", () => {
const value = sortSelect.value;
let sortBy = "name";
let sortDir = "asc";
if (value === "name_asc") {
sortBy = "name";
sortDir = "asc";
} else if (value === "name_desc") {
sortBy = "name";
sortDir = "desc";
}
window.location.href = `${uploadUrl}?sort_by=${sortBy}&sort_dir=${sortDir}`;
});
}
// Recursively walk a dropped DataTransferItem (file or directory) into
// a flat list of File objects, using the browser's non-standard but
// widely-supported webkitGetAsEntry/FileSystemEntry APIs to support
// dragging & dropping whole folders.
function readEntry(entry: FileSystemEntry): Promise<File[]> {
return new Promise((resolve) => {
if (entry.isFile) {
@@ -178,6 +170,8 @@
}
}
if (entries.length === 0) {
// Fallback for browsers without webkitGetAsEntry support: flat
// files only, no folder traversal.
void upload(Array.from(e.dataTransfer?.files || []));
return;
}