diff --git a/PLAN.md b/PLAN.md index 258e491..bbaf5a6 100644 --- a/PLAN.md +++ b/PLAN.md @@ -89,6 +89,12 @@ scripts/sync-collabry.sh copies them from upstream at a pinned commit the migrations on start (`src/db/index.ts`). - [x] 12. Renamed from "Home Dashboard" to Dahoam (slug `dahoam`): package, compose project, tab title, default dashboard name, docs, CI examples. +- [x] 13. Dashboards: table `dashboard`, `card.dashboardId`, `settings.defaultDashboardId` + (migration `0006_dashboards_icons` puts the existing cards on a dashboard "Home"). `/?d=` + opens one, `/` the default. Switcher in the header, managed in Settings → Dashboards. +- [x] 14. Icons: the link dialog searches dashboard-icons (`src/lib/icons.ts` and its test) and + uploads custom icons (table `icon`, `/api/icon`, ≤ 1 MB, SVG allowed because it is served + sandboxed). `src/lib/upload.ts` holds the upload checks that wallpaper and icons share. ## Not doing (not asked) @@ -96,5 +102,8 @@ scripts/sync-collabry.sh copies them from upstream at a pinned commit - Inline SearXNG result rendering (search opens the engine's result page) - Reordering the cards themselves (they stay in the order they were made), free placement with gaps in the grid, per-user SearXNG URL (SSRF risk — it is a server env) +- Per dashboard wallpaper, clock or search engine (they stay per user), moving a card to another + dashboard, reordering dashboards, remembering the last opened dashboard (the default opens) +- A list of the icons a user uploaded, to use one again for another link - Email verification / password reset mail (needs an SMTP setup) - In CI: version tags and releases, a Helm chart, an image vulnerability scan (typst-workspace has all three) diff --git a/README.md b/README.md index 5af1fe9..9528c02 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,10 @@ Build it yourself: `docker build -t dahoam .` ## Use +- **Dashboards** are separate sets of cards, for example Home and Work. Settings → Dashboards + adds, renames and deletes them and sets the default, the one that opens when you sign in. + With more than one, switch at the top of the page or with `/switch to work`. The address + of a dashboard (`/?d=…`) can be bookmarked. Wallpaper, clock and search are the same on all. - **Cards** group your links (Apps, Media, Bookmarks, ...). "New card" under the cards adds one. Click a card's name to rename or delete it. - **Links**: **+** at the top or on a card adds a link. Hover a link and click the pencil to @@ -61,9 +65,10 @@ Build it yourself: `docker build -t dahoam .` Keyboard: focus a link, Space picks it up, arrow keys move it, Space puts it down. - **Icons**: leave the field empty and the icon is looked up by name in [dashboard-icons](https://github.com/homarr-labs/dashboard-icons), then from the - site's `/favicon.ico`. Or enter an icon name (`home-assistant`) or an image URL. + site's `/favicon.ico`. Or type in the field to search that library and click an icon, + paste an image URL, or upload your own image (PNG, JPEG, WebP, AVIF or SVG, up to 1 MB). - **Search**: `/` focuses the bar. `!w cats` uses DuckDuckGo bangs. `/plex` jumps to - a link, `/settings`, `/add link`, `/add card` and `/sign out` run commands. + a link, `/settings`, `/add link`, `/add card`, `/add dashboard` and `/sign out` run commands. - **Wallpaper**: Settings (or the pencil at the bottom right) takes an image URL or an upload (JPEG, PNG, WebP, AVIF, up to 10 MB). A slider sets how much it is darkened. - **Clock**: Settings has five fonts and three styles. Glass shows the wallpaper blurred @@ -75,7 +80,10 @@ Build it yourself: `docker build -t dahoam .` selected engine. The server fetches them, the browser never calls those hosts directly. - SSO does not take over an existing password account with the same email (Better Auth blocks it, because password emails are not verified). Use one or the other per email. -- Icon lookups send the link name to the jsDelivr CDN. +- Icon lookups send the link name to the jsDelivr CDN. The link dialog also loads the + library's list of icons from there. +- Uploaded icons are stored in Postgres and only their owner can load them. One that no + link uses any more is deleted with that user's next upload. - UI components come from [collabry-components](https://git.nhaiden.io/niklas/collabry-components), copied into `src/vendor/collabry` at a pinned commit. Add or update one with `scripts/sync-collabry.sh` (see `src/vendor/collabry/UPSTREAM.md`). The glass look is diff --git a/drizzle/0006_dashboards_icons.sql b/drizzle/0006_dashboards_icons.sql new file mode 100644 index 0000000..0b62d5a --- /dev/null +++ b/drizzle/0006_dashboards_icons.sql @@ -0,0 +1,30 @@ +CREATE TABLE "dashboard" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" text NOT NULL, + "name" text NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "icon" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" text NOT NULL, + "mime" text NOT NULL, + "data" "bytea" NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "card" ADD COLUMN "dashboard_id" uuid;--> statement-breakpoint +-- Hand-written: the cards a user already has become that user's first dashboard, "Home". +INSERT INTO "dashboard" ("user_id", "name") + SELECT DISTINCT "user_id", 'Home' FROM "card";--> statement-breakpoint +UPDATE "card" SET "dashboard_id" = "dashboard"."id" FROM "dashboard" + WHERE "dashboard"."user_id" = "card"."user_id";--> statement-breakpoint +ALTER TABLE "card" ALTER COLUMN "dashboard_id" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "settings" ADD COLUMN "default_dashboard_id" uuid;--> statement-breakpoint +ALTER TABLE "dashboard" ADD CONSTRAINT "dashboard_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "icon" ADD CONSTRAINT "icon_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "dashboard_user_id_idx" ON "dashboard" USING btree ("user_id");--> statement-breakpoint +CREATE INDEX "icon_user_id_idx" ON "icon" USING btree ("user_id");--> statement-breakpoint +ALTER TABLE "card" ADD CONSTRAINT "card_dashboard_id_dashboard_id_fk" FOREIGN KEY ("dashboard_id") REFERENCES "public"."dashboard"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "settings" ADD CONSTRAINT "settings_default_dashboard_id_dashboard_id_fk" FOREIGN KEY ("default_dashboard_id") REFERENCES "public"."dashboard"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "card_dashboard_id_idx" ON "card" USING btree ("dashboard_id"); \ No newline at end of file diff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..681c799 --- /dev/null +++ b/drizzle/meta/0006_snapshot.json @@ -0,0 +1,883 @@ +{ + "id": "7a2af09b-64c1-4ae0-8b47-a669a9e399f0", + "prevId": "4df576be-2fef-462c-affd-4aff0ab26918", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.card": { + "name": "card", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dashboard_id": { + "name": "dashboard_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "card_user_id_idx": { + "name": "card_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "card_dashboard_id_idx": { + "name": "card_dashboard_id_idx", + "columns": [ + { + "expression": "dashboard_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "card_user_id_user_id_fk": { + "name": "card_user_id_user_id_fk", + "tableFrom": "card", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "card_dashboard_id_dashboard_id_fk": { + "name": "card_dashboard_id_dashboard_id_fk", + "tableFrom": "card", + "tableTo": "dashboard", + "columnsFrom": [ + "dashboard_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard": { + "name": "dashboard", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "dashboard_user_id_idx": { + "name": "dashboard_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_user_id_user_id_fk": { + "name": "dashboard_user_id_user_id_fk", + "tableFrom": "dashboard", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.icon": { + "name": "icon", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "icon_user_id_idx": { + "name": "icon_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "icon_user_id_user_id_fk": { + "name": "icon_user_id_user_id_fk", + "tableFrom": "icon", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.link": { + "name": "link", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "card_id": { + "name": "card_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "link_user_id_idx": { + "name": "link_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "link_card_id_idx": { + "name": "link_card_id_idx", + "columns": [ + { + "expression": "card_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "link_user_id_user_id_fk": { + "name": "link_user_id_user_id_fk", + "tableFrom": "link", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "link_card_id_card_id_fk": { + "name": "link_card_id_card_id_fk", + "tableFrom": "link", + "tableTo": "card", + "columnsFrom": [ + "card_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'Dahoam'" + }, + "default_dashboard_id": { + "name": "default_dashboard_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "search_engine": { + "name": "search_engine", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'duckduckgo'" + }, + "wallpaper_url": { + "name": "wallpaper_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "wallpaper_dim": { + "name": "wallpaper_dim", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 40 + }, + "clock_font": { + "name": "clock_font", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'serif'" + }, + "clock_style": { + "name": "clock_style", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'solid'" + } + }, + "indexes": {}, + "foreignKeys": { + "settings_user_id_user_id_fk": { + "name": "settings_user_id_user_id_fk", + "tableFrom": "settings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "settings_default_dashboard_id_dashboard_id_fk": { + "name": "settings_default_dashboard_id_dashboard_id_fk", + "tableFrom": "settings", + "tableTo": "dashboard", + "columnsFrom": [ + "default_dashboard_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wallpaper": { + "name": "wallpaper", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "bytea", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "wallpaper_user_id_user_id_fk": { + "name": "wallpaper_user_id_user_id_fk", + "tableFrom": "wallpaper", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 82d4e29..07574d2 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1795017884385, "tag": "0005_wallpaper_dim", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1795020380796, + "tag": "0006_dashboards_icons", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/components/card-dialog.tsx b/src/components/card-dialog.tsx index 4c6ea92..27bd552 100644 --- a/src/components/card-dialog.tsx +++ b/src/components/card-dialog.tsx @@ -21,19 +21,28 @@ import { export type CardTarget = { id: string; name: string; links: unknown[] } | "new" -/** `card` is the card to edit, "new" to add one, or null when closed. */ +/** + * `card` is the card to edit, "new" to add one, or null when closed. + * A new card goes on the dashboard `dashboardId`. + */ export function CardDialog({ card, + dashboardId, onClose, }: { card: CardTarget | null + dashboardId: string onClose: () => void }) { return ( !open && onClose()}> {card && ( - + )} @@ -42,9 +51,11 @@ export function CardDialog({ function CardForm({ card, + dashboardId, onClose, }: { card: Exclude | null + dashboardId: string onClose: () => void }) { const router = useRouter() @@ -72,7 +83,9 @@ function CardForm({ onSubmit={(e) => { e.preventDefault() const name = String(new FormData(e.currentTarget).get("name")) - void submit(() => saveCard({ data: { id: card?.id, name } })) + void submit(() => + saveCard({ data: { id: card?.id, name, dashboardId } }) + ) }} > diff --git a/src/components/link-dialog.tsx b/src/components/link-dialog.tsx index 0d0072f..b020458 100644 --- a/src/components/link-dialog.tsx +++ b/src/components/link-dialog.tsx @@ -1,9 +1,16 @@ -import { useState } from "react" +import { useEffect, useRef, useState } from "react" import { useRouter } from "@tanstack/react-router" -import { Trash2 } from "lucide-react" +import { Trash2, Upload, X } from "lucide-react" import { GlassDialogContent } from "@/components/glass" import type { HomeLink } from "@/components/link-tile" import { deleteLink, saveLink } from "@/lib/dashboard.functions" +import { + LIBRARY_INDEX, + UPLOADED_ICON, + isImageAddress, + libraryIcon, + searchIcons, +} from "@/lib/icons" import { Button } from "@/vendor/collabry/components/Button/Button" import { Field, @@ -38,7 +45,8 @@ export function LinkDialog({ }) { return ( !open && onClose()}> - + {/* taller than a small screen since it shows icons: scroll inside */} + {target && } @@ -58,6 +66,41 @@ function LinkForm({ const router = useRouter() const [busy, setBusy] = useState(false) const [error, setError] = useState("") + const [name, setName] = useState(link?.name ?? "") + const [icon, setIcon] = useState(link?.icon ?? "") + const [library, setLibrary] = useState([]) + const file = useRef(null) + + // Without the library's index the field still takes a name or an address. + useEffect(() => { + fetch(LIBRARY_INDEX) + .then((res) => res.json()) + .then((index: { png: string[] }) => + setLibrary(index.png.map((f) => f.replace(/\.png$/, ""))) + ) + .catch(() => {}) + }, []) + + const uploaded = icon.startsWith(UPLOADED_ICON) + // what the field holds, or what an empty field would look up + const matches = isImageAddress(icon) ? [] : searchIcons(library, icon || name) + + const upload = async (image: File) => { + setBusy(true) + setError("") + try { + const res = await fetch("/api/icon", { + method: "POST", + headers: { "Content-Type": image.type }, + body: image, + }) + if (res.ok) setIcon((await res.json()).icon) + else setError(await res.text()) + } catch { + setError("Could not upload. Try again.") + } + setBusy(false) + } const submit = async (action: () => Promise) => { setBusy(true) @@ -82,9 +125,9 @@ function LinkForm({ data: { id: link?.id, cardId: String(form.get("cardId")), - name: String(form.get("name")), + name, url: String(form.get("url")), - icon: String(form.get("icon")).trim() || null, + icon: icon.trim() || null, }, }) ) @@ -100,8 +143,8 @@ function LinkForm({ Name setName(e.target.value)} placeholder="Plex" maxLength={60} required @@ -123,13 +166,79 @@ function LinkForm({ Icon (optional) - +
+ {uploaded && ( + + )} + setIcon(e.target.value)} + placeholder={ + uploaded ? "Your image" : "Search icons or paste a URL" + } + autoComplete="off" + /> + {uploaded && ( + + )} + { + const image = e.target.files?.[0] + if (image) void upload(image) + e.target.value = "" + }} + /> + +
+ {matches.length > 0 && ( + // two and a half rows, so it shows that there is more to scroll to +
+ {matches.map((match) => ( + + ))} +
+ )} - Empty: found from the name, then from the site's favicon. + Empty: found from the name, then from the site's favicon. Upload a + PNG, JPEG, WebP, AVIF or SVG, up to 1 MB.
diff --git a/src/components/link-tile.tsx b/src/components/link-tile.tsx index 36afd36..51fa70b 100644 --- a/src/components/link-tile.tsx +++ b/src/components/link-tile.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react" import { useSortable } from "@dnd-kit/sortable" import { CSS } from "@dnd-kit/utilities" import { Pencil } from "lucide-react" +import { iconSources } from "@/lib/icons" import { cn } from "@/vendor/collabry/lib/cn" export type HomeLink = { @@ -12,21 +13,6 @@ export type HomeLink = { icon: string | null } -const dashboardIcon = (name: string) => - `https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/${name - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, "")}.png` - -/** Icon sources to try in order; the letter tile is the last resort. */ -function iconSources({ name, url, icon }: HomeLink) { - return [ - icon && /^https?:\/\//.test(icon) ? icon : dashboardIcon(icon || name), - `${new URL(url).origin}/favicon.ico`, - ] -} - type IconProps = { link: HomeLink; className?: string } /** Starts the fallback chain again when the link changes. */ diff --git a/src/db/schema.ts b/src/db/schema.ts index a1ff2aa..d51a57b 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -77,9 +77,9 @@ export const verification = pgTable( const bytea = customType<{ data: Uint8Array }>({ dataType: () => "bytea" }) -/** A named group of links on the dashboard. */ -export const card = pgTable( - "card", +/** A set of cards, for example Home and Work. */ +export const dashboard = pgTable( + "dashboard", { id: uuid("id").primaryKey().defaultRandom(), userId: text("user_id") @@ -88,7 +88,27 @@ export const card = pgTable( name: text("name").notNull(), createdAt: timestamp("created_at").notNull().defaultNow(), }, - (t) => [index("card_user_id_idx").on(t.userId)] + (t) => [index("dashboard_user_id_idx").on(t.userId)] +) + +/** A named group of links on a dashboard. */ +export const card = pgTable( + "card", + { + id: uuid("id").primaryKey().defaultRandom(), + userId: text("user_id") + .notNull() + .references(() => user.id, { onDelete: "cascade" }), + dashboardId: uuid("dashboard_id") + .notNull() + .references(() => dashboard.id, { onDelete: "cascade" }), + name: text("name").notNull(), + createdAt: timestamp("created_at").notNull().defaultNow(), + }, + (t) => [ + index("card_user_id_idx").on(t.userId), + index("card_dashboard_id_idx").on(t.dashboardId), + ] ) export const link = pgTable( @@ -105,7 +125,8 @@ export const link = pgTable( position: integer("position").notNull().default(0), name: text("name").notNull(), url: text("url").notNull(), - // image URL or a dashboard-icons name ("plex"); null = guess from name + // image URL, an upload ("/api/icon?id=…") or a dashboard-icons name ("plex"); + // null = guess from name icon: text("icon"), createdAt: timestamp("created_at").notNull().defaultNow(), }, @@ -120,6 +141,11 @@ export const settings = pgTable("settings", { .primaryKey() .references(() => user.id, { onDelete: "cascade" }), title: text("title").notNull().default("Dahoam"), + // the dashboard that opens after sign-in; null = the oldest one + defaultDashboardId: uuid("default_dashboard_id").references( + () => dashboard.id, + { onDelete: "set null" } + ), searchEngine: text("search_engine", { enum: ["duckduckgo", "searxng", "google"], }) @@ -140,6 +166,21 @@ export const settings = pgTable("settings", { .default("solid"), }) +/** A link icon that the user uploaded, served from /api/icon. */ +export const icon = pgTable( + "icon", + { + id: uuid("id").primaryKey().defaultRandom(), + userId: text("user_id") + .notNull() + .references(() => user.id, { onDelete: "cascade" }), + mime: text("mime").notNull(), + data: bytea("data").notNull(), + createdAt: timestamp("created_at").notNull().defaultNow(), + }, + (t) => [index("icon_user_id_idx").on(t.userId)] +) + export const wallpaper = pgTable("wallpaper", { userId: text("user_id") .primaryKey() diff --git a/src/lib/dashboard.functions.ts b/src/lib/dashboard.functions.ts index 9487aac..e3669ac 100644 --- a/src/lib/dashboard.functions.ts +++ b/src/lib/dashboard.functions.ts @@ -4,7 +4,7 @@ import { and, asc, eq, inArray, sql } from "drizzle-orm" import { z } from "zod" import { DEFAULT_WALLPAPER_DIM } from "@/components/wallpaper" import { db } from "@/db" -import { card, link, settings, wallpaper } from "@/db/schema" +import { card, dashboard, link, settings, wallpaper } from "@/db/schema" import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth" import { CLOCK_FONTS, CLOCK_STYLES } from "@/lib/clock" import { ENGINES, parseSuggestions } from "@/lib/search" @@ -19,6 +19,14 @@ async function requireCard(userId: string, cardId: string) { if (!found.length) throw new Error("Unknown card") } +async function requireDashboard(userId: string, dashboardId: string) { + const found = await db + .select({ id: dashboard.id }) + .from(dashboard) + .where(and(eq(dashboard.id, dashboardId), eq(dashboard.userId, userId))) + if (!found.length) throw new Error("Unknown dashboard") +} + /** The position after the last link of a card. */ const endOf = (cardId: string) => sql`(select coalesce(max(${link.position}) + 1, 0) from ${link} where ${link.cardId} = ${cardId})` @@ -31,17 +39,44 @@ export const getAuthInfo = createServerFn({ method: "GET" }).handler( }) ) -/** Everything the dashboard renders, or null when signed out. */ -export const getDashboard = createServerFn({ method: "GET" }).handler( - async () => { +/** + * Everything the dashboard renders, or null when signed out. Without a + * `dashboardId`, or with one that does not exist, it is the default dashboard. + */ +export const getDashboard = createServerFn({ method: "GET" }) + // any string: the id comes from the address bar, a wrong one is not an error + .validator(z.object({ dashboardId: z.string().optional() }).optional()) + .handler(async ({ data }) => { const session = await auth.api.getSession({ headers: getRequestHeaders() }) if (!session) return null const userId = session.user.id - const [cards, links, rows] = await Promise.all([ + const [dashboards, rows] = await Promise.all([ + db + .select({ id: dashboard.id, name: dashboard.name }) + .from(dashboard) + .where(eq(dashboard.userId, userId)) + .orderBy(asc(dashboard.createdAt)), + db.select().from(settings).where(eq(settings.userId, userId)), + ]) + // Cards need a dashboard and links need a card, so nobody is left without one. + // shortcut: two first loads at the same moment make two of each, add a unique + // constraint if that ever shows up + if (!dashboards.length) + dashboards.push( + ...(await db + .insert(dashboard) + .values({ userId, name: "Home" }) + .returning({ id: dashboard.id, name: dashboard.name })) + ) + const s = rows.at(0) // no row until the first save + const has = (id?: string | null) => dashboards.find((d) => d.id === id)?.id + const defaultDashboardId = has(s?.defaultDashboardId) ?? dashboards[0].id + const dashboardId = has(data?.dashboardId) ?? defaultDashboardId + const [cards, links] = await Promise.all([ db .select({ id: card.id, name: card.name }) .from(card) - .where(eq(card.userId, userId)) + .where(and(eq(card.userId, userId), eq(card.dashboardId, dashboardId))) .orderBy(asc(card.createdAt)), db .select({ @@ -52,23 +87,22 @@ export const getDashboard = createServerFn({ method: "GET" }).handler( icon: link.icon, }) .from(link) - .where(eq(link.userId, userId)) + .innerJoin(card, eq(card.id, link.cardId)) + .where(and(eq(link.userId, userId), eq(card.dashboardId, dashboardId))) .orderBy(asc(link.position), asc(link.createdAt)), - db.select().from(settings).where(eq(settings.userId, userId)), ]) - // Links need a card to live in, so nobody is left without one. - // shortcut: two first loads at the same moment make two cards, add a unique - // constraint if that ever shows up if (!cards.length) cards.push( ...(await db .insert(card) - .values({ userId, name: "Apps" }) + .values({ userId, dashboardId, name: "Apps" }) .returning({ id: card.id, name: card.name })) ) - const s = rows.at(0) // no row until the first save return { user: { name: session.user.name, email: session.user.email }, + dashboards, + dashboardId, + defaultDashboardId, cards: cards.map((c) => ({ ...c, links: links.filter((l) => l.cardId === c.id), @@ -81,8 +115,7 @@ export const getDashboard = createServerFn({ method: "GET" }).handler( clockStyle: s?.clockStyle ?? "solid", searxngUrl: process.env.SEARXNG_URL || null, } - } -) + }) export const saveLink = createServerFn({ method: "POST" }) .validator( @@ -119,9 +152,11 @@ export const saveCard = createServerFn({ method: "POST" }) z.object({ id: z.uuid().optional(), name: z.string().trim().min(1).max(40), + // where a new card goes. A card that exists stays on its dashboard. + dashboardId: z.uuid(), }) ) - .handler(async ({ data: { id, name } }) => { + .handler(async ({ data: { id, name, dashboardId } }) => { const user = await requireUser() if (id) { await db @@ -129,10 +164,41 @@ export const saveCard = createServerFn({ method: "POST" }) .set({ name }) .where(and(eq(card.id, id), eq(card.userId, user.id))) } else { - await db.insert(card).values({ name, userId: user.id }) + await requireDashboard(user.id, dashboardId) + await db.insert(card).values({ name, dashboardId, userId: user.id }) } }) +export const saveDashboard = createServerFn({ method: "POST" }) + .validator( + z.object({ + id: z.uuid().optional(), + name: z.string().trim().min(1).max(40), + }) + ) + .handler(async ({ data: { id, name } }) => { + const user = await requireUser() + if (id) { + await db + .update(dashboard) + .set({ name }) + .where(and(eq(dashboard.id, id), eq(dashboard.userId, user.id))) + } else { + await db.insert(dashboard).values({ name, userId: user.id }) + } + }) + +/** Deletes the dashboard and, through the foreign keys, its cards and their links. */ +export const deleteDashboard = createServerFn({ method: "POST" }) + .validator(z.object({ id: z.uuid() })) + .handler(async ({ data }) => { + const user = await requireUser() + const mine = eq(dashboard.userId, user.id) + if ((await db.$count(dashboard, mine)) < 2) + throw new Error("The last dashboard stays") + await db.delete(dashboard).where(and(eq(dashboard.id, data.id), mine)) + }) + /** Deletes the card and, through the foreign key, its links. */ export const deleteCard = createServerFn({ method: "POST" }) .validator(z.object({ id: z.uuid() })) @@ -187,6 +253,7 @@ export const saveSettings = createServerFn({ method: "POST" }) z .object({ title: z.string().trim().min(1).max(40), + defaultDashboardId: z.uuid(), searchEngine: z.enum(ENGINES), // external image, the user's own upload, or null for the default wallpaperUrl: z @@ -201,6 +268,8 @@ export const saveSettings = createServerFn({ method: "POST" }) ) .handler(async ({ data }) => { const user = await requireUser() + if (data.defaultDashboardId) + await requireDashboard(user.id, data.defaultDashboardId) await db .insert(settings) .values({ ...data, userId: user.id }) diff --git a/src/lib/icons.test.ts b/src/lib/icons.test.ts new file mode 100644 index 0000000..041d4b1 --- /dev/null +++ b/src/lib/icons.test.ts @@ -0,0 +1,35 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { UPLOADED_ICON, iconSources, searchIcons } from "./icons.ts" + +const link = { name: "Home Assistant", url: "https://ha.example.com/lovelace" } +const first = (icon: string | null) => iconSources({ ...link, icon })[0] + +test("no icon: looked up by name, then the site's favicon", () => { + assert.deepEqual(iconSources({ ...link, icon: null }), [ + "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/home-assistant.png", + "https://ha.example.com/favicon.ico", + ]) +}) + +test("an icon name is looked up in the library", () => { + assert.match(first(" Plex "), /\/png\/plex\.png$/) +}) + +test("an image address and an upload are used as they are", () => { + assert.equal(first("https://example.com/a.png"), "https://example.com/a.png") + assert.equal(first(`${UPLOADED_ICON}abc`), "/api/icon?id=abc") +}) + +test("searchIcons: names that start with the query first, the shortest first", () => { + // the order of the library's index: "plex-alt" is before "plex" there + const names = ["a-plex", "jellyfin", "plex-alt", "plex", "plexamp"] + assert.deepEqual(searchIcons(names, "Plex"), [ + "plex", + "plexamp", + "plex-alt", + "a-plex", + ]) + assert.deepEqual(searchIcons(names, "plex", 2), ["plex", "plexamp"]) + assert.deepEqual(searchIcons(names, "nothing"), []) +}) diff --git a/src/lib/icons.ts b/src/lib/icons.ts new file mode 100644 index 0000000..58dae01 --- /dev/null +++ b/src/lib/icons.ts @@ -0,0 +1,51 @@ +// Where a link's icon comes from. Pure, so it can be tested without a browser. + +const LIBRARY = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons" + +/** JSON with the file names of every icon in the library: `{ png: ["plex.png", …] }`. */ +export const LIBRARY_INDEX = `${LIBRARY}/tree.json` + +/** How a link stores an icon that the user uploaded: this plus the icon's id. */ +export const UPLOADED_ICON = "/api/icon?id=" + +const slug = (name: string) => + name + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") + +export const libraryIcon = (name: string) => `${LIBRARY}/png/${slug(name)}.png` + +/** An image address or an upload, not a name in the library. */ +export const isImageAddress = (icon: string) => + /^https?:\/\//.test(icon) || icon.startsWith(UPLOADED_ICON) + +/** Icon sources to try in order; the letter tile is the last resort. */ +export function iconSources({ + name, + url, + icon, +}: { + name: string + url: string + icon: string | null +}) { + return [ + icon && isImageAddress(icon) ? icon : libraryIcon(icon || name), + `${new URL(url).origin}/favicon.ico`, + ] +} + +/** + * Library icons for what the user typed: names that start with it, then names that + * contain it. In both groups the shortest first, so "plex" is before "plex-alt". + */ +export function searchIcons(names: string[], query: string, limit = 42) { + const q = slug(query) + const rank = (n: string) => (n.startsWith(q) ? 0 : 1000) + n.length + return names + .filter((n) => n.includes(q)) + .sort((a, b) => rank(a) - rank(b)) + .slice(0, limit) +} diff --git a/src/lib/upload.ts b/src/lib/upload.ts new file mode 100644 index 0000000..c7a3d61 --- /dev/null +++ b/src/lib/upload.ts @@ -0,0 +1,49 @@ +// Shared by the routes that store images in the database (wallpaper, link icons). +import { auth } from "@/lib/auth" + +export async function userId(request: Request) { + const session = await auth.api.getSession({ headers: request.headers }) + return session?.user.id +} + +/** The image in the body of an upload, or the response that says why it was refused. */ +export async function readImage( + request: Request, + limits: { types: string[]; formats: string; maxMb: number } +) { + const id = await userId(request) + if (!id) return new Response("Unauthorized", { status: 401 }) + const mime = request.headers.get("content-type") ?? "" + if (!limits.types.includes(mime)) + return new Response(`Use a ${limits.formats} image`, { status: 415 }) + const maxBytes = limits.maxMb * 1024 * 1024 + const tooLarge = () => + new Response(`Image is empty or larger than ${limits.maxMb} MB`, { + status: 413, + }) + // a chunked body has no declared size and could fill the memory + const declared = Number(request.headers.get("content-length")) + if ( + !(declared > 0 && declared <= maxBytes) || + request.headers.has("transfer-encoding") + ) + return tooLarge() + const data = new Uint8Array(await request.arrayBuffer()) + if (!data.length || data.length > maxBytes) return tooLarge() + return { userId: id, mime, data } +} + +/** Answers with a stored image. Its URL has to change when the image does. */ +export const serveImage = (row?: { mime: string; data: Uint8Array }) => + row + ? new Response(new Uint8Array(row.data), { + headers: { + "Content-Type": row.mime, + "X-Content-Type-Options": "nosniff", + // an SVG that is opened in its own tab must not run scripts on this origin + "Content-Security-Policy": + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + "Cache-Control": "private, max-age=31536000, immutable", + }, + }) + : new Response("Not found", { status: 404 }) diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index 0a5658b..bae71a5 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as LoginRouteImport } from './routes/login' import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ApiIconRouteImport } from './routes/api/icon' import { Route as ApiWallpaperRouteImport } from './routes/api/wallpaper' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' @@ -30,6 +31,11 @@ const SettingsRoute = SettingsRouteImport.update({ path: '/settings', getParentRoute: () => rootRouteImport, } as any) +const ApiIconRoute = ApiIconRouteImport.update({ + id: '/api/icon', + path: '/api/icon', + getParentRoute: () => rootRouteImport, +} as any) const ApiWallpaperRoute = ApiWallpaperRouteImport.update({ id: '/api/wallpaper', path: '/api/wallpaper', @@ -45,6 +51,7 @@ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/login': typeof LoginRoute '/settings': typeof SettingsRoute + '/api/icon': typeof ApiIconRoute '/api/wallpaper': typeof ApiWallpaperRoute '/api/auth/$': typeof ApiAuthSplatRoute } @@ -52,6 +59,7 @@ export interface FileRoutesByTo { '/': typeof IndexRoute '/login': typeof LoginRoute '/settings': typeof SettingsRoute + '/api/icon': typeof ApiIconRoute '/api/wallpaper': typeof ApiWallpaperRoute '/api/auth/$': typeof ApiAuthSplatRoute } @@ -60,22 +68,42 @@ export interface FileRoutesById { '/': typeof IndexRoute '/login': typeof LoginRoute '/settings': typeof SettingsRoute + '/api/icon': typeof ApiIconRoute '/api/wallpaper': typeof ApiWallpaperRoute '/api/auth/$': typeof ApiAuthSplatRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$' + fullPaths: + | '/' + | '/login' + | '/settings' + | '/api/icon' + | '/api/wallpaper' + | '/api/auth/$' fileRoutesByTo: FileRoutesByTo - to: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$' + to: + | '/' + | '/login' + | '/settings' + | '/api/icon' + | '/api/wallpaper' + | '/api/auth/$' id: - '__root__' | '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$' + | '__root__' + | '/' + | '/login' + | '/settings' + | '/api/icon' + | '/api/wallpaper' + | '/api/auth/$' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute LoginRoute: typeof LoginRoute SettingsRoute: typeof SettingsRoute + ApiIconRoute: typeof ApiIconRoute ApiWallpaperRoute: typeof ApiWallpaperRoute ApiAuthSplatRoute: typeof ApiAuthSplatRoute } @@ -103,6 +131,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } + '/api/icon': { + id: '/api/icon' + path: '/api/icon' + fullPath: '/api/icon' + preLoaderRoute: typeof ApiIconRouteImport + parentRoute: typeof rootRouteImport + } '/api/wallpaper': { id: '/api/wallpaper' path: '/api/wallpaper' @@ -124,6 +159,7 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, LoginRoute: LoginRoute, SettingsRoute: SettingsRoute, + ApiIconRoute: ApiIconRoute, ApiWallpaperRoute: ApiWallpaperRoute, ApiAuthSplatRoute: ApiAuthSplatRoute, } diff --git a/src/routes/api/icon.ts b/src/routes/api/icon.ts new file mode 100644 index 0000000..1009459 --- /dev/null +++ b/src/routes/api/icon.ts @@ -0,0 +1,63 @@ +import { createFileRoute } from "@tanstack/react-router" +import { and, eq, sql } from "drizzle-orm" +import { z } from "zod" +import { db } from "@/db" +import { icon, link } from "@/db/schema" +import { UPLOADED_ICON } from "@/lib/icons" +import { readImage, serveImage, userId } from "@/lib/upload" + +const LIMITS = { + // SVG is safe here: serveImage sandboxes it + types: [ + "image/png", + "image/jpeg", + "image/webp", + "image/avif", + "image/svg+xml", + ], + formats: "PNG, JPEG, WebP, AVIF or SVG", + maxMb: 1, +} + +export const Route = createFileRoute("/api/icon")({ + server: { + handlers: { + GET: async ({ request }) => { + const user = await userId(request) + if (!user) return new Response("Unauthorized", { status: 401 }) + const id = z + .uuid() + .safeParse(new URL(request.url).searchParams.get("id")) + if (!id.success) return new Response("Not found", { status: 404 }) + return serveImage( + ( + await db + .select() + .from(icon) + .where(and(eq(icon.id, id.data), eq(icon.userId, user))) + ).at(0) + ) + }, + POST: async ({ request }) => { + const image = await readImage(request, LIMITS) + if (image instanceof Response) return image + // Icons that no link uses any more go away with the next upload. An hour of + // grace, because a new icon has no link until its dialog is saved. + // shortcut: no limit on uploads per user, add one if strangers can sign up + await db.execute(sql` + delete from ${icon} + where ${icon.userId} = ${image.userId} + and ${icon.createdAt} < now() - interval '1 hour' + and not exists ( + select 1 from ${link} + where ${link.icon} = ${UPLOADED_ICON} || ${icon.id}::text + )`) + const [row] = await db + .insert(icon) + .values(image) + .returning({ id: icon.id }) + return Response.json({ icon: UPLOADED_ICON + row.id }) + }, + }, + }, +}) diff --git a/src/routes/api/wallpaper.ts b/src/routes/api/wallpaper.ts index b01c0da..ea69097 100644 --- a/src/routes/api/wallpaper.ts +++ b/src/routes/api/wallpaper.ts @@ -2,70 +2,43 @@ import { createFileRoute } from "@tanstack/react-router" import { eq } from "drizzle-orm" import { db } from "@/db" import { settings, wallpaper } from "@/db/schema" -import { auth } from "@/lib/auth" +import { readImage, serveImage, userId } from "@/lib/upload" -const MAX_BYTES = 10 * 1024 * 1024 -// no SVG: it can carry scripts -const TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] - -async function userId(request: Request) { - const session = await auth.api.getSession({ headers: request.headers }) - return session?.user.id +const LIMITS = { + // no SVG: a wallpaper is a photo + types: ["image/jpeg", "image/png", "image/webp", "image/avif"], + formats: "JPEG, PNG, WebP or AVIF", + maxMb: 10, } export const Route = createFileRoute("/api/wallpaper")({ server: { handlers: { + // the URL carries ?v=, so it never changes GET: async ({ request }) => { const id = await userId(request) if (!id) return new Response("Unauthorized", { status: 401 }) - const row = ( - await db.select().from(wallpaper).where(eq(wallpaper.userId, id)) - ).at(0) - if (!row) return new Response("Not found", { status: 404 }) - return new Response(new Uint8Array(row.data), { - headers: { - "Content-Type": row.mime, - "X-Content-Type-Options": "nosniff", - // the URL carries ?v=, so it never changes - "Cache-Control": "private, max-age=31536000, immutable", - }, - }) + return serveImage( + ( + await db.select().from(wallpaper).where(eq(wallpaper.userId, id)) + ).at(0) + ) }, POST: async ({ request }) => { - const id = await userId(request) - if (!id) return new Response("Unauthorized", { status: 401 }) - const mime = request.headers.get("content-type") ?? "" - if (!TYPES.includes(mime)) - return new Response("Use a JPEG, PNG, WebP or AVIF image", { - status: 415, - }) - // a chunked body has no declared size and could fill the memory - const declared = Number(request.headers.get("content-length")) - if ( - !(declared > 0 && declared <= MAX_BYTES) || - request.headers.has("transfer-encoding") - ) - return new Response("Image is empty or larger than 10 MB", { - status: 413, - }) - const data = new Uint8Array(await request.arrayBuffer()) - if (!data.length || data.length > MAX_BYTES) - return new Response("Image is empty or larger than 10 MB", { - status: 413, - }) + const image = await readImage(request, LIMITS) + if (image instanceof Response) return image const wallpaperUrl = `/api/wallpaper?v=${Date.now()}` await db.transaction(async (tx) => { await tx .insert(wallpaper) - .values({ userId: id, mime, data }) + .values(image) .onConflictDoUpdate({ target: wallpaper.userId, - set: { mime, data }, + set: { mime: image.mime, data: image.data }, }) await tx .insert(settings) - .values({ userId: id, wallpaperUrl }) + .values({ userId: image.userId, wallpaperUrl }) .onConflictDoUpdate({ target: settings.userId, set: { wallpaperUrl }, diff --git a/src/routes/index.tsx b/src/routes/index.tsx index aae5533..c72433e 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -5,7 +5,14 @@ import { redirect, useRouter, } from "@tanstack/react-router" -import { LayoutGrid, LogOut, Pencil, Plus, Settings2 } from "lucide-react" +import { + LayoutDashboard, + LayoutGrid, + LogOut, + Pencil, + Plus, + Settings2, +} from "lucide-react" import { CardDialog } from "@/components/card-dialog" import type { CardTarget } from "@/components/card-dialog" import { CardGrid } from "@/components/card-grid" @@ -21,8 +28,12 @@ import { Button } from "@/vendor/collabry/components/Button/Button" import { cn } from "@/vendor/collabry/lib/cn" export const Route = createFileRoute("/")({ - loader: async () => { - const data = await getDashboard() + // ?d=. Without it the default dashboard opens. + validateSearch: (search): { d?: string } => + typeof search.d === "string" ? { d: search.d } : {}, + loaderDeps: ({ search }) => search, + loader: async ({ deps }) => { + const data = await getDashboard({ data: { dashboardId: deps.d } }) if (!data) throw redirect({ to: "/login" }) return data }, @@ -50,14 +61,33 @@ function Dashboard() {

{data.title}

- + {data.dashboards.length > 1 && ( + + )} + {/* at the right, so it does not read as one more dashboard */} + {data.user.name} + + + + ) + })} + +
{ + e.preventDefault() + const form = e.currentTarget + const name = String(new FormData(form).get("name")) + void run(() => saveDashboard({ data: { name } })).then( + () => form.reset() + ) + }} + > + + +
+
+ + Clock