8 Commits

Author SHA1 Message Date
0f65bfb94a feat(web): native favorites, lightbox zoom, EXIF jump links + perf fix
- Favorites use PhotoPrism's own like/unlike endpoint (not a mule-only
  mark) so they sync to third-party gallery apps, with heart controls
  in the tile, sidebar, and an `f` shortcut.
- Lightbox: wheel-zoom around cursor, double-click to 2.5x, drag-to-pan,
  auto-upgrades to the fit_2048 tile past 1.25x zoom.
- Sidebar: copy-EXIF button, clickable Camera/Lens values that jump to
  a filtered timeline (camera:/lens: DSL), matching the existing
  Country link.
- Fix filtersToQ() quoting the entire search string whenever it
  contained a colon, which silently turned any raw DSL operator
  (camera:, taken:2024, etc.) into a literal phrase search — discovered
  while verifying the new jump-links against production.
- Disable TanStack Query's refetchOnWindowFocus: the indexer WebSocket
  already invalidates photo queries on real changes, so the focus
  refetch was just a redundant full-timeline re-render on tab-switch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 21:56:49 +02:00
9ba8d625bc feat(web): ⌘K command palette
bits-ui Command in a dialog: jump to sections, heaps, folders (from the
already-warm sidebar queries), plus dark-mode and shortcut-overlay
actions. Global ⌘K binding in the layout works from any route and while
inputs hold focus.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:22:31 +02:00
4f04c1f7b0 feat(web): toolbar filter chips (type/year/favorites) + timeline sort control
Chips compile into the existing q-DSL alongside search/folder/section
terms and persist to the URL. Sort (newest/oldest/added/name) threads
through the sidecar timeline's order param; deep-link anchor windows
stay newest-only.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:19:47 +02:00
9ef1b4c2f9 feat(web): keyboard rating/color marks, search focus, shortcuts overlay
Lightroom-style keys in grid+preview: 0-5 rating (re-key toggles),
6-9 color labels, optimistic marks cache patch with rollback. / focuses
the search box, ? opens a new shortcut-reference overlay that inertly
swallows other keys while open.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:15:00 +02:00
ac7d0ac2eb docs: mobile & third-party app setup with per-user scoping
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:10:59 +02:00
312a4c1ee4 feat(sidecar): extend scoped proxy to web-client mutations, harden path classification
Batch archive/restore/delete/approve/private validate every UID against
the PhotoPrism DB in one query. Per-photo PUT/approve/like/stack-file
ops are ownership-checked. Admin-role sessions pass through fully so
settings/users/index dialogs keep working. Paths are unescaped+cleaned
before classification so encoded dot-segments can't smuggle past the
allowlist. Full httptest coverage of the routing decisions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 13:05:12 +02:00
e578e1ce75 feat(sidecar): scoped PhotoPrism-compatible API proxy for third-party apps
PhotoPrism CE doesn't enforce auth_users.base_path on API reads (any
user can q=path:"other/*"). New /api/v1/* proxy forwards to PhotoPrism
with per-session enforcement: search queries get their path filter
validated/injected, single-photo reads and like are ownership-checked,
hash-addressed media and session/config pass through, everything else
is 403 for scoped users. Admins (empty BasePath) pass through fully.
prism.hubris.network will route here instead of straight to PhotoPrism.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:59:19 +02:00
6cbabda86b feat(sidecar): enforce per-user BasePath on all filesystem mutations
Folder create/rename/delete/move, photo move, heap convert, and file
rename now reject paths outside the caller's BasePath (403). Sources
resolved via PhotoPrism UIDs are re-checked in movePhotoFiles. The
USER_BASEPATHS reconciler also sets upload_path so client-app uploads
land inside the user's subtree.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:46:00 +02:00
30 changed files with 1771 additions and 98 deletions

View File

@@ -102,6 +102,35 @@ labels still work; the following sidecar endpoints return an OS error:
PhotoPrism's `PHOTOPRISM_READONLY` is controlled separately by
`PP_READONLY` and gates its own backwrite / import paths.
## Mobile & third-party apps (per-user)
PhotoPrism CE does **not** enforce `auth_users.base_path` on API reads —
any authenticated user can search the whole library. The sidecar
therefore ships a scoping proxy at `/api/v1/*` (see
[`sidecar/handlers_ppproxy.go`](sidecar/handlers_ppproxy.go)) and the
reverse proxy routes the public `/api/v1` there instead of straight to
PhotoPrism. Result: any PhotoPrism-compatible app pointed at the site
sees only the logged-in user's photos.
- **Server URL for apps**: the site itself (e.g.
`https://photos.hubris.network`). Known-good client:
[Gallery for PhotoPrism](https://github.com/Radiokot/photoprism-android-client)
(Android/F-Droid).
- **Login**: the user's normal username/password. For OIDC accounts (no
password), mint an app password:
`docker exec pp-app photoprism auth add -n "gallery" -s "*" <username>`
and use it as the password in the app.
- **What's scoped**: photo/geo searches, per-photo reads and edits,
batch operations, downloads by UID. Hash-addressed media (thumbnails,
video streams, file downloads) is token-guarded and passes through.
- **What's shared** (CE has no per-user variants of these): album
*names*, labels, and people — the photos inside them stay scoped.
Album zip downloads are generated by PhotoPrism and are not scoped.
- **Uploads**: the reconciler mirrors `base_path` into `upload_path`,
so WebDAV/app uploads land inside the user's own subtree.
- Sessions with the `admin` role bypass the proxy scoping entirely (the
web client's settings/users/index dialogs need the raw API).
## Dev iteration loop
For fast iteration on the sidecar without rebuilding its image on every

View File

@@ -2,6 +2,8 @@ package main
import (
"net/http"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
@@ -85,3 +87,35 @@ func ctxBasePath(c *gin.Context) string {
}
return s
}
// userScopeRoot returns the absolute directory the session may mutate:
// ORIGINALS_ROOT/<BasePath> for scoped users, the whole originals root for
// admins (empty BasePath). Lexical join only — callers compare it against
// paths built the same way from cfg.OriginalsRoot.
func userScopeRoot(c *gin.Context, cfg *Config) string {
base := strings.Trim(ctxBasePath(c), "/")
if base == "" {
return cfg.OriginalsRoot
}
return filepath.Join(cfg.OriginalsRoot, base)
}
// requireUserScope guards an already-root-resolved absolute path against
// the caller's BasePath. PhotoPrism scopes what a session can *see* by
// BasePath, but the sidecar's filesystem endpoints accept raw paths, so
// every mutation must re-check that boundary here. `strict` additionally
// rejects the scope root itself — renaming/deleting/moving the user's own
// base folder would detach their library from auth_users.base_path.
// Writes the 403 response and returns false when out of bounds.
func requireUserScope(c *gin.Context, cfg *Config, abs string, strict bool) bool {
scope := userScopeRoot(c, cfg)
if !sameOrUnder(abs, scope) {
c.JSON(http.StatusForbidden, gin.H{"error": "path outside your library"})
return false
}
if strict && abs == scope {
c.JSON(http.StatusForbidden, gin.H{"error": "cannot modify your library root"})
return false
}
return true
}

50
sidecar/auth_test.go Normal file
View File

@@ -0,0 +1,50 @@
package main
import (
"net/http/httptest"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
func scopeCtx(basePath string) *gin.Context {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Set("basePath", basePath)
return c
}
func TestRequireUserScope(t *testing.T) {
cfg := &Config{OriginalsRoot: filepath.FromSlash("/originals")}
abs := func(rel string) string { return filepath.Join(cfg.OriginalsRoot, filepath.FromSlash(rel)) }
cases := []struct {
name string
basePath string
path string
strict bool
want bool
}{
{"admin sees root", "", cfg.OriginalsRoot, false, true},
{"admin anywhere", "", abs("bob/x"), false, true},
{"admin strict rejects root", "", cfg.OriginalsRoot, true, false},
{"scoped inside own tree", "alice", abs("alice/2024"), false, true},
{"scoped own root non-strict", "alice", abs("alice"), false, true},
{"scoped own root strict", "alice", abs("alice"), true, false},
{"scoped other user", "alice", abs("bob/2024"), false, false},
{"scoped sibling prefix", "alice", abs("alice2/2024"), false, false},
{"scoped originals root", "alice", cfg.OriginalsRoot, false, false},
{"nested base path", "family/alice", abs("family/alice/x"), false, true},
{"nested base path parent", "family/alice", abs("family"), false, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := scopeCtx(tc.basePath)
if got := requireUserScope(c, cfg, tc.path, tc.strict); got != tc.want {
t.Errorf("requireUserScope(base=%q, path=%q, strict=%v) = %v, want %v",
tc.basePath, tc.path, tc.strict, got, tc.want)
}
})
}
}

View File

@@ -25,10 +25,10 @@ type dupFileLite struct {
}
type dupGroup struct {
Hash string `json:"hash"`
Size int64 `json:"size"`
IndexedPath *string `json:"indexedPath"`
Files []dupFileLite `json:"files"`
Hash string `json:"hash"`
Size int64 `json:"size"`
IndexedPath *string `json:"indexedPath"`
Files []dupFileLite `json:"files"`
}
// dupListPhoto is the partial photo shape we pull from PhotoPrism when

View File

@@ -47,6 +47,9 @@ func handleFolderCreate(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid path"})
return
}
if !requireUserScope(c, cfg, abs, true) {
return
}
if _, err := os.Stat(abs); err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "already exists"})
return
@@ -92,6 +95,9 @@ func handleFolderRename(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid path"})
return
}
if !requireUserScope(c, cfg, oldAbs, true) {
return
}
st, err := os.Stat(oldAbs)
if err != nil || !st.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a directory"})
@@ -142,6 +148,9 @@ func handleFolderDelete(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "refuse to delete root"})
return
}
if !requireUserScope(c, cfg, abs, true) {
return
}
st, err := os.Stat(abs)
if err != nil || !st.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a directory"})

View File

@@ -90,6 +90,9 @@ func handleHeapConvert(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid targetFolder"})
return
}
if !requireUserScope(c, cfg, targetAbs, false) {
return
}
// Pull the heap's membership via the q=album:UID query (count=1000
// covers every realistic heap). We only need the UID list here — the
// search's Files array is trimmed and drops videos, so we re-resolve
@@ -124,7 +127,7 @@ func handleHeapConvert(cfg *Config, pp *ppClient) gin.HandlerFunc {
return
}
moved, copied, errs, err := movePhotoFiles(cfg, pp, token, photos, targetAbs, subfolder, mode)
moved, copied, errs, err := movePhotoFiles(cfg, pp, token, photos, targetAbs, subfolder, mode, userScopeRoot(c, cfg))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -167,7 +170,10 @@ func handleHeapConvert(cfg *Config, pp *ppClient) gin.HandlerFunc {
// and handlePhotosMove (UID-list scoped); both resolve `photos` differently
// but move them identically. Returns per-photo errors in `errs`; the returned
// top-level error is only for a fatal precondition (subfolder mkdir failed).
func movePhotoFiles(cfg *Config, pp *ppClient, token string, photos []heapPhoto, targetAbs, subfolder, mode string) (moved, copied int, errs []heapErr, err error) {
// `scopeAbs` is the caller's userScopeRoot — source files outside it fail
// per-photo, so a UID that resolves outside the user's BasePath (however
// PhotoPrism came to return it) can't be used to pull files across users.
func movePhotoFiles(cfg *Config, pp *ppClient, token string, photos []heapPhoto, targetAbs, subfolder, mode, scopeAbs string) (moved, copied int, errs []heapErr, err error) {
destAbs := targetAbs
if subfolder != "" {
destAbs = filepath.Join(targetAbs, subfolder)
@@ -234,8 +240,8 @@ func movePhotoFiles(cfg *Config, pp *ppClient, token string, photos []heapPhoto,
for _, f := range group {
srcRel := f.Name
srcAbs := filepath.Join(cfg.OriginalsRoot, srcRel)
if !sameOrUnder(srcAbs, cfg.OriginalsRoot) {
failure = "path escapes originals"
if !sameOrUnder(srcAbs, scopeAbs) {
failure = "path outside your library"
break
}
st, statErr := os.Stat(srcAbs)

View File

@@ -115,14 +115,14 @@ func handleLabels(pp *ppClient, ppDb *gorm.DB) gin.HandlerFunc {
// PpCounts mirrors PhotoPrism's session config.count block that drives
// the sidebar badges (review, archive, all, etc.).
type PpCounts struct {
All int `json:"all"`
Photos int `json:"photos"`
Media int `json:"media"`
Videos int `json:"videos"`
Review int `json:"review"`
Archived int `json:"archived"`
Hidden int `json:"hidden"`
Private int `json:"private"`
All int `json:"all"`
Photos int `json:"photos"`
Media int `json:"media"`
Videos int `json:"videos"`
Review int `json:"review"`
Archived int `json:"archived"`
Hidden int `json:"hidden"`
Private int `json:"private"`
Favorites int `json:"favorites"`
}

View File

@@ -56,6 +56,9 @@ func handlePhotosMove(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid targetFolder"})
return
}
if !requireUserScope(c, cfg, targetAbs, false) {
return
}
// Resolve each photo's FULL file list via the single-photo endpoint
// rather than the /photos search (see resolvePhotosFull) — the search
@@ -67,7 +70,7 @@ func handlePhotosMove(cfg *Config, pp *ppClient) gin.HandlerFunc {
return
}
moved, copied, errs, err := movePhotoFiles(cfg, pp, token, photos, targetAbs, subfolder, mode)
moved, copied, errs, err := movePhotoFiles(cfg, pp, token, photos, targetAbs, subfolder, mode, userScopeRoot(c, cfg))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -148,6 +151,9 @@ func handleFolderMove(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid path"})
return
}
if !requireUserScope(c, cfg, oldAbs, true) {
return
}
st, err := os.Stat(oldAbs)
if err != nil || !st.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a directory"})
@@ -158,6 +164,9 @@ func handleFolderMove(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid targetParent"})
return
}
if !requireUserScope(c, cfg, targetParentAbs, false) {
return
}
// Can't move a folder into itself or one of its own descendants.
if sameOrUnder(targetParentAbs, oldAbs) {
c.JSON(http.StatusBadRequest, gin.H{"error": "cannot move a folder into itself"})

354
sidecar/handlers_ppproxy.go Normal file
View File

@@ -0,0 +1,354 @@
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httputil"
"net/url"
gopath "path"
"regexp"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Scoped PhotoPrism-compatible API proxy.
//
// PhotoPrism CE does not enforce auth_users.base_path on API reads — any
// authenticated user can search the whole library (`q=path:"other/*"`),
// verified empirically against this deployment. The web client compensates
// by post-filtering inside /api/sidecar/*, but third-party PhotoPrism apps
// (Gallery for PhotoPrism, Photo Uploader, …) speak to /api/v1 directly.
//
// This proxy is the public face for those apps. It forwards /api/v1/* to
// PhotoPrism with these rules for sessions that carry a BasePath:
//
// - search endpoints (photos, geo) get their `path` filter rewritten so
// results stay inside the caller's BasePath subtree;
// - per-photo reads and mutations the web client needs (metadata PUT,
// approve, like, stack file ops) are ownership-checked per UID;
// - batch archive/restore/delete validates every UID in the body against
// the PhotoPrism DB before forwarding;
// - hash-addressed media (t/, dl/, videos/) and session/config pass
// through — media URLs embed per-instance preview/download tokens and
// unguessable content hashes, the same protection PhotoPrism's own
// share links rely on;
// - album + label + subject reads and album/subject mutations pass
// through: PhotoPrism CE has no per-user albums or faces, so these are
// shared across users by design; the photos inside stay path-scoped;
// - everything else (settings, users, index, import, uploads) answers 403.
//
// Admin-role sessions (and any session without a BasePath) pass through
// fully — the web client's admin dialogs (settings, users, indexing) need
// the raw API.
// ppQPathTerm matches a `path:` filter inside PhotoPrism's q-DSL — either
// quoted (path:"a b/*") or bare (path:a/*).
var ppQPathTerm = regexp.MustCompile(`(?i)\bpath:("[^"]*"|\S+)`)
// pathValueAllowed reports whether one path-filter value stays inside base.
// PhotoPrism ORs `|`-separated alternatives inside a single value, so every
// alternative must pass. A bare `base*` (no slash) is rejected because the
// wildcard would also match sibling folders like `base2/…`.
func pathValueAllowed(val, base string) bool {
val = strings.Trim(val, `"`)
for _, alt := range strings.Split(val, "|") {
v := strings.Trim(strings.TrimSpace(alt), "/")
if v == base {
continue
}
if strings.HasPrefix(v, base+"/") {
continue
}
return false
}
return true
}
// scopeQ rewrites a q-DSL string so its path filter cannot leave base.
// User-supplied path terms that already stay inside base are kept (the web
// client and gallery apps use them for folder drills); any term that
// escapes — or the absence of one — collapses to `path:"base/*"`.
func scopeQ(q, base string) string {
terms := ppQPathTerm.FindAllStringSubmatch(q, -1)
if len(terms) > 0 {
ok := true
for _, m := range terms {
if !pathValueAllowed(m[1], base) {
ok = false
break
}
}
if ok {
return q
}
q = strings.TrimSpace(ppQPathTerm.ReplaceAllString(q, ""))
}
scope := ` path:"` + strings.ReplaceAll(base, `"`, "") + `/*"`
return strings.TrimSpace(q + scope)
}
// scopeSearchValues enforces the BasePath on a search request's query
// string. The q-DSL `path:` term overrides the `path` form parameter in
// PhotoPrism's parser (verified empirically), so the guarantee lives in q;
// the standalone param is validated too so it can't disagree.
func scopeSearchValues(v url.Values, base string) url.Values {
v.Set("q", scopeQ(v.Get("q"), base))
if p := v.Get("path"); p != "" && !pathValueAllowed(p, base) {
v.Del("path")
}
return v
}
// ppProxyPhoto is the projection needed for per-UID ownership checks.
type ppProxyPhoto struct {
Path string `json:"Path"`
Files []ppFile `json:"Files"`
}
// photoWithinBase fetches one photo with the caller's own token and checks
// that it lives inside base. Fails closed on any error.
func photoWithinBase(ctx context.Context, pp *ppClient, token, uid, base string) bool {
resp, err := pp.call(ctx, http.MethodGet, "/api/v1/photos/"+url.PathEscape(uid), token, nil)
if err != nil || !resp.OK {
return false
}
var p ppProxyPhoto
if err := json.Unmarshal(resp.Body, &p); err != nil {
return false
}
if p.Path != "" {
return p.Path == base || strings.HasPrefix(p.Path, base+"/")
}
for _, f := range p.Files {
if f.Root == "/" && strings.HasPrefix(f.Name, base+"/") {
return true
}
}
return false
}
// cachedSession is a short-lived token→user cache so a burst of gallery
// requests doesn't double every call with a /session probe. 60s matches
// the BasePath reconciler cadence; a revoked token lives at most that long.
type cachedSession struct {
user *ppSessionUser
expiry time.Time
}
type sessionCache struct {
mu sync.Mutex
m map[string]cachedSession
}
func (sc *sessionCache) resolve(ctx context.Context, pp *ppClient, token string) *ppSessionUser {
if token == "" {
return nil
}
now := time.Now()
sc.mu.Lock()
if e, ok := sc.m[token]; ok && now.Before(e.expiry) {
sc.mu.Unlock()
return e.user
}
sc.mu.Unlock()
user := pp.resolveSession(ctx, token)
if user == nil {
return nil
}
sc.mu.Lock()
if len(sc.m) > 1024 { // hard cap; sessions are few, tokens churn rarely
sc.m = map[string]cachedSession{}
}
sc.m[token] = cachedSession{user: user, expiry: now.Add(60 * time.Second)}
sc.mu.Unlock()
return user
}
// proxyToken pulls the session token from any header form PhotoPrism
// clients use: X-Auth-Token (canonical), Authorization: Bearer, or the
// legacy X-Session-ID.
func proxyToken(r *http.Request) string {
if t := r.Header.Get("X-Auth-Token"); t != "" {
return t
}
if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") {
return strings.TrimPrefix(a, "Bearer ")
}
return r.Header.Get("X-Session-ID")
}
// batchUIDsWithinBase validates that every photo UID in a batch body lives
// under base, using one SQL query against PhotoPrism's photos table. Fails
// closed: no DB handle, unknown UIDs, or any path outside base → false.
func batchUIDsWithinBase(ppDb *gorm.DB, uids []string, base string) bool {
if ppDb == nil || len(uids) == 0 {
return false
}
var n int64
err := ppDb.Table("photos").
Where("photo_uid IN ?", uids).
Where("photo_path = ? OR photo_path LIKE ?", base, base+"/%").
Count(&n).Error
if err != nil {
slog.Warn("pp-proxy: batch ownership query failed", "err", err)
return false
}
return n == int64(len(uids))
}
// readBatchBody consumes the request body, extracts the `photos` UID list,
// and reinstates the body so the proxy can still forward it.
func readBatchBody(r *http.Request) ([]string, bool) {
buf, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
r.Body.Close()
r.Body = io.NopCloser(bytes.NewReader(buf))
r.ContentLength = int64(len(buf))
if err != nil {
return nil, false
}
var body struct {
Photos []string `json:"photos"`
}
if err := json.Unmarshal(buf, &body); err != nil {
return nil, false
}
return body.Photos, true
}
// handlePPProxy returns the gin handler mounted at /api/v1/*rest.
func handlePPProxy(cfg *Config, ppDb *gorm.DB) gin.HandlerFunc {
target, err := url.Parse(cfg.PhotoprismBaseURL)
if err != nil {
slog.Error("pp-proxy: bad PHOTOPRISM_BASE_URL", "err", err)
return func(c *gin.Context) { c.AbortWithStatus(http.StatusBadGateway) }
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
slog.Warn("pp-proxy: upstream error", "path", r.URL.Path, "err", err)
w.WriteHeader(http.StatusBadGateway)
}
// Ownership checks reuse the normal client; a dedicated instance would
// gain nothing.
pp := newPPClient(cfg.PhotoprismBaseURL)
cache := &sessionCache{m: map[string]cachedSession{}}
forbid := func(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusForbidden,
gin.H{"error": "not available through this proxy"})
}
return func(c *gin.Context) {
// The router keeps raw escapes (UseRawPath). Unescape and clean
// before classifying, then forward exactly the cleaned path — so
// `t%2F..%2Fsettings` can't be classified as media here yet reach
// /settings after PhotoPrism's own router cleans it.
unesc, err := url.PathUnescape(c.Param("rest"))
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "bad path"})
return
}
rest := strings.TrimPrefix(gopath.Clean("/"+unesc), "/")
c.Request.URL.Path = "/api/v1/" + rest
c.Request.URL.RawPath = ""
method := c.Request.Method
// Unauthenticated / token-in-URL surface: login+logout, client
// config, hash-addressed media, websocket.
passUnscoped := rest == "session" || strings.HasPrefix(rest, "session/") ||
strings.HasPrefix(rest, "oauth/") ||
rest == "config" || rest == "ws" ||
strings.HasPrefix(rest, "t/") ||
strings.HasPrefix(rest, "dl/") ||
strings.HasPrefix(rest, "videos/") ||
strings.HasPrefix(rest, "svg/")
if passUnscoped {
proxy.ServeHTTP(c.Writer, c.Request)
return
}
user := cache.resolve(c.Request.Context(), pp, proxyToken(c.Request))
if user == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
base := strings.Trim(user.BasePath, "/")
if base == "" || user.Role == "admin" {
// Admins keep the raw API — the web client's settings, users,
// and indexing dialogs need it. (On this deployment the admin
// account carries a BasePath purely to default its web view.)
proxy.ServeHTTP(c.Writer, c.Request)
return
}
isGet := method == http.MethodGet || method == http.MethodHead
switch {
// Search endpoints: enforce the path scope inside the query.
case isGet && (rest == "photos" || rest == "photos/view" || rest == "geo"):
q := c.Request.URL.Query()
c.Request.URL.RawQuery = scopeSearchValues(q, base).Encode()
proxy.ServeHTTP(c.Writer, c.Request)
// Batch mutations: every UID in the body must be the caller's.
case method == http.MethodPost && (rest == "batch/photos/archive" ||
rest == "batch/photos/restore" || rest == "batch/photos/delete" ||
rest == "batch/photos/approve" || rest == "batch/photos/private"):
uids, ok := readBatchBody(c.Request)
if !ok || !batchUIDsWithinBase(ppDb, uids, base) {
forbid(c)
return
}
proxy.ServeHTTP(c.Writer, c.Request)
// Per-photo operations: ownership-checked per UID. Covers reads,
// metadata PUT, approve, like/unlike, download, and the stack file
// ops (set primary / unstack / delete file) the review UI uses.
case strings.HasPrefix(rest, "photos/"):
parts := strings.Split(rest, "/")
uid := parts[1]
var allowed bool
switch len(parts) {
case 2:
allowed = isGet || method == http.MethodPut
case 3:
allowed = (isGet && parts[2] == "dl") ||
(method == http.MethodPost && parts[2] == "approve") ||
(parts[2] == "like" && (method == http.MethodPost || method == http.MethodDelete))
case 4:
allowed = method == http.MethodDelete && parts[2] == "files"
case 5:
allowed = method == http.MethodPost && parts[2] == "files" &&
(parts[4] == "primary" || parts[4] == "unstack")
}
if !allowed {
forbid(c)
return
}
if !photoWithinBase(c.Request.Context(), pp, proxyToken(c.Request), uid, base) {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "photo not found"})
return
}
proxy.ServeHTTP(c.Writer, c.Request)
// Albums (heaps), labels, subjects, faces: shared across users by
// design in CE — reads and mutations pass through; the photos inside
// any of them stay path-scoped by the rules above.
case rest == "albums" || strings.HasPrefix(rest, "albums/") ||
rest == "labels" || strings.HasPrefix(rest, "labels/") ||
rest == "subjects" || strings.HasPrefix(rest, "subjects/") ||
rest == "faces" || strings.HasPrefix(rest, "faces/"):
proxy.ServeHTTP(c.Writer, c.Request)
default:
slog.Info("pp-proxy: blocked", "user", user.UserName, "method", method, "path", rest)
forbid(c)
}
}
}

View File

@@ -0,0 +1,222 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestScopeQ(t *testing.T) {
cases := []struct {
name string
q string
base string
want string
}{
{"empty q gains scope", "", "dtoro", `path:"dtoro/*"`},
{"plain search gains scope", "label:dog", "dtoro", `label:dog path:"dtoro/*"`},
{"inside path kept", `path:"dtoro/2024/*" label:dog`, "dtoro", `path:"dtoro/2024/*" label:dog`},
{"exact base kept", `path:"dtoro"`, "dtoro", `path:"dtoro"`},
{"outside path replaced", `path:"muli/*"`, "dtoro", `path:"dtoro/*"`},
{"bare term outside replaced", `path:muli/x label:dog`, "dtoro", `label:dog path:"dtoro/*"`},
{"pipe alternative escaping", `path:"dtoro/*|muli/*"`, "dtoro", `path:"dtoro/*"`},
{"pipe all inside kept", `path:"dtoro/a|dtoro/b/*"`, "dtoro", `path:"dtoro/a|dtoro/b/*"`},
{"sibling prefix rejected", `path:"dtoro2/*"`, "dtoro", `path:"dtoro/*"`},
{"bare wildcard on base rejected", `path:dtoro*`, "dtoro", `path:"dtoro/*"`},
{"mixed valid+invalid terms collapse", `path:"dtoro/a" path:"muli/b"`, "dtoro", `path:"dtoro/*"`},
{"case-insensitive filter name", `PATH:"muli/*"`, "dtoro", `path:"dtoro/*"`},
{"nested base", `path:"family/alice/x"`, "family/alice", `path:"family/alice/x"`},
{"nested base parent escape", `path:"family/*"`, "family/alice", `path:"family/alice/*"`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := scopeQ(tc.q, tc.base); got != tc.want {
t.Errorf("scopeQ(%q, %q) = %q, want %q", tc.q, tc.base, got, tc.want)
}
})
}
}
func TestScopeSearchValues(t *testing.T) {
v := url.Values{}
v.Set("count", "60")
v.Set("path", "muli/*")
got := scopeSearchValues(v, "dtoro")
if got.Get("path") != "" {
t.Errorf("outside path param should be dropped, got %q", got.Get("path"))
}
if got.Get("q") != `path:"dtoro/*"` {
t.Errorf("q should carry the scope, got %q", got.Get("q"))
}
if got.Get("count") != "60" {
t.Errorf("unrelated params must survive, got count=%q", got.Get("count"))
}
v2 := url.Values{}
v2.Set("path", "dtoro/2024")
got2 := scopeSearchValues(v2, "dtoro")
if got2.Get("path") != "dtoro/2024" {
t.Errorf("inside path param should be kept, got %q", got2.Get("path"))
}
}
// fakePP stands in for PhotoPrism: answers /session per token, echoes
// every other request's method+path+query back as JSON.
func fakePP(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/session" && r.Method == http.MethodGet {
var user map[string]any
switch r.Header.Get("X-Auth-Token") {
case "tok-scoped":
user = map[string]any{"UID": "u1", "Name": "alice", "Role": "user", "BasePath": "alice"}
case "tok-admin":
user = map[string]any{"UID": "u0", "Name": "root", "Role": "admin", "BasePath": "alice"}
default:
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"user": user})
return
}
if strings.HasPrefix(r.URL.Path, "/api/v1/photos/") && r.Method == http.MethodGet &&
strings.Count(r.URL.Path, "/") == 4 {
uid := strings.TrimPrefix(r.URL.Path, "/api/v1/photos/")
path := "alice/2024"
if strings.HasPrefix(uid, "foreign") {
path = "bob/2024"
}
json.NewEncoder(w).Encode(map[string]any{"Path": path})
return
}
json.NewEncoder(w).Encode(map[string]any{
"echo": r.Method + " " + r.URL.Path,
"query": r.URL.RawQuery,
"handled": true,
})
}))
}
func proxyRig(t *testing.T) (*httptest.Server, func()) {
t.Helper()
up := fakePP(t)
cfg := &Config{PhotoprismBaseURL: up.URL}
gin.SetMode(gin.TestMode)
r := gin.New()
r.UseRawPath = true
r.UnescapePathValues = false
r.Any("/api/v1/*rest", handlePPProxy(cfg, nil))
front := httptest.NewServer(r)
return front, func() { front.Close(); up.Close() }
}
func proxyReq(t *testing.T, front, method, path, token string) (int, string) {
t.Helper()
req, _ := http.NewRequest(method, front+path, nil)
if token != "" {
req.Header.Set("X-Auth-Token", token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var sb strings.Builder
buf := make([]byte, 4096)
for {
n, err := resp.Body.Read(buf)
sb.Write(buf[:n])
if err != nil {
break
}
}
return resp.StatusCode, sb.String()
}
func TestProxyRouting(t *testing.T) {
front, done := proxyRig(t)
defer done()
t.Run("media passes unauthenticated", func(t *testing.T) {
code, body := proxyReq(t, front.URL, "GET", "/api/v1/t/abc/tok/tile_224", "")
if code != 200 || !strings.Contains(body, "/api/v1/t/abc/tok/tile_224") {
t.Errorf("thumb should pass through, got %d %s", code, body)
}
})
t.Run("scoped search gains path scope", func(t *testing.T) {
code, body := proxyReq(t, front.URL, "GET", "/api/v1/photos?count=3&q="+url.QueryEscape(`path:"bob/*"`), "tok-scoped")
if code != 200 {
t.Fatalf("got %d", code)
}
var out struct{ Query string }
json.Unmarshal([]byte(body), &out)
q, _ := url.ParseQuery(out.Query)
if q.Get("q") != `path:"alice/*"` {
t.Errorf("escaping q must collapse to own scope, got %q", q.Get("q"))
}
})
t.Run("scoped settings blocked", func(t *testing.T) {
code, _ := proxyReq(t, front.URL, "GET", "/api/v1/settings", "tok-scoped")
if code != http.StatusForbidden {
t.Errorf("settings should 403 for scoped user, got %d", code)
}
})
t.Run("admin settings passes", func(t *testing.T) {
code, body := proxyReq(t, front.URL, "GET", "/api/v1/settings", "tok-admin")
if code != 200 || !strings.Contains(body, "/api/v1/settings") {
t.Errorf("admin should pass through, got %d %s", code, body)
}
})
t.Run("no token unauthorized", func(t *testing.T) {
code, _ := proxyReq(t, front.URL, "GET", "/api/v1/photos", "")
if code != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", code)
}
})
t.Run("own photo readable, foreign 404", func(t *testing.T) {
code, _ := proxyReq(t, front.URL, "GET", "/api/v1/photos/mine123", "tok-scoped")
if code != 200 {
t.Errorf("own photo should pass, got %d", code)
}
code, _ = proxyReq(t, front.URL, "GET", "/api/v1/photos/foreign9", "tok-scoped")
if code != http.StatusNotFound {
t.Errorf("foreign photo should 404, got %d", code)
}
})
t.Run("encoded traversal cannot reach settings as media", func(t *testing.T) {
code, _ := proxyReq(t, front.URL, "GET", "/api/v1/t%2F..%2Fsettings", "tok-scoped")
if code != http.StatusForbidden {
t.Errorf("traversal should classify as settings and 403, got %d", code)
}
})
t.Run("batch without db fails closed", func(t *testing.T) {
req, _ := http.NewRequest("POST", front.URL+"/api/v1/batch/photos/archive",
strings.NewReader(`{"photos":["p1"]}`))
req.Header.Set("X-Auth-Token", "tok-scoped")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("batch with nil ppDb must 403, got %d", resp.StatusCode)
}
})
}
func TestPathValueAllowed(t *testing.T) {
if pathValueAllowed(`"muli/*"`, "dtoro") {
t.Error("outside value must be rejected")
}
if !pathValueAllowed(`"dtoro/Photos/2024"`, "dtoro") {
t.Error("inside value must be allowed")
}
if pathValueAllowed("dtoro/a|muli/b", "dtoro") {
t.Error("any escaping pipe alternative must reject the whole value")
}
}

View File

@@ -97,6 +97,9 @@ func handleRename(cfg *Config, pp *ppClient) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": "path escapes originals root"})
return
}
if !requireUserScope(c, cfg, oldAbs, false) {
return
}
st, err := os.Stat(oldAbs)
if err != nil || !st.Mode().IsRegular() {
c.JSON(http.StatusNotFound, gin.H{"error": "file missing on disk"})

View File

@@ -79,49 +79,55 @@ func main() {
// Every other endpoint runs behind the session gate. Mounting them
// under one group keeps the middleware wiring obvious.
auth := r.Group("/api/sidecar", requireSession(pp))
{
auth.GET("/prefs", handlePrefsGet(db))
auth.PUT("/prefs", handlePrefsPut(cfg, db))
auth := r.Group("/api/sidecar", requireSession(pp))
{
auth.GET("/prefs", handlePrefsGet(db))
auth.PUT("/prefs", handlePrefsPut(cfg, db))
auth.GET("/photos/marks", handleMarksAll(db))
auth.GET("/photos/:uid/marks", handleMarkGet(db))
auth.PUT("/photos/:uid/marks", handleMarkPut(db))
auth.POST("/photos/marks/bulk", handleMarkBulk(db))
auth.GET("/photos/marks", handleMarksAll(db))
auth.GET("/photos/:uid/marks", handleMarkGet(db))
auth.PUT("/photos/:uid/marks", handleMarkPut(db))
auth.POST("/photos/marks/bulk", handleMarkBulk(db))
auth.POST("/files/:uid/rename", handleRename(cfg, pp))
auth.POST("/files/:uid/rename", handleRename(cfg, pp))
auth.POST("/folders", handleFolderCreate(cfg, pp))
auth.POST("/folders/counts", handleFolderCounts(pp))
auth.POST("/folders/:rel/rename", handleFolderRename(cfg, pp))
auth.POST("/folders/:rel/move", handleFolderMove(cfg, pp))
auth.DELETE("/folders/:rel", handleFolderDelete(cfg, pp))
auth.POST("/folders", handleFolderCreate(cfg, pp))
auth.POST("/folders/counts", handleFolderCounts(pp))
auth.POST("/folders/:rel/rename", handleFolderRename(cfg, pp))
auth.POST("/folders/:rel/move", handleFolderMove(cfg, pp))
auth.DELETE("/folders/:rel", handleFolderDelete(cfg, pp))
auth.POST("/albums/:uid/convert", handleHeapConvert(cfg, pp))
auth.POST("/photos/move", handlePhotosMove(cfg, pp))
auth.POST("/albums/:uid/convert", handleHeapConvert(cfg, pp))
auth.POST("/photos/move", handlePhotosMove(cfg, pp))
auth.GET("/duplicates/scan", handleDupScan(cfg, pp, db))
auth.POST("/duplicates/archive", handleDupArchive(cfg, pp, db))
auth.GET("/duplicates/scan", handleDupScan(cfg, pp, db))
auth.POST("/duplicates/archive", handleDupArchive(cfg, pp, db))
// User-scoped proxies — require PpDSN connection.
if ppDb != nil {
auth.GET("/labels", handleLabels(pp, ppDb))
auth.GET("/counts", handleScopedCounts(ppDb))
auth.GET("/countries", handleCountries(ppDb))
}
// User-scoped proxies — require PpDSN connection.
if ppDb != nil {
auth.GET("/labels", handleLabels(pp, ppDb))
auth.GET("/counts", handleScopedCounts(ppDb))
auth.GET("/countries", handleCountries(ppDb))
}
// User-scoped photos — post-filters by BasePath so review/archive
// tabs only show photos the user owns.
auth.GET("/timeline", handlePhotos(pp))
// User-scoped photos — post-filters by BasePath so review/archive
// tabs only show photos the user owns.
auth.GET("/timeline", handlePhotos(pp))
// Photos carrying a Note (Caption) — pages PhotoPrism fully so
// the /notes view isn't capped to the newest slice.
auth.GET("/notes", handleNotes(pp))
// Photos carrying a Note (Caption) — pages PhotoPrism fully so
// the /notes view isn't capped to the newest slice.
auth.GET("/notes", handleNotes(pp))
// User-scoped folders — post-filters the folder tree by BasePath
// so the sidebar shows only folders under the user's library root.
auth.GET("/folders", handleFoldersProxy(pp))
}
// User-scoped folders — post-filters the folder tree by BasePath
// so the sidebar shows only folders under the user's library root.
auth.GET("/folders", handleFoldersProxy(pp))
}
// PhotoPrism-compatible scoped proxy — the public /api/v1 surface for
// both the web client and third-party PhotoPrism apps (Caddy routes
// /api/v1 here instead of straight to PhotoPrism, which does not
// enforce base_path in CE). See handlers_ppproxy.go for the rules.
r.Any("/api/v1/*rest", handlePPProxy(cfg, ppDb))
addr := cfg.ListenAddr + ":" + itoa(cfg.Port)
srv := &http.Server{
@@ -154,4 +160,3 @@ func main() {
}
<-idleClosed
}

View File

@@ -90,6 +90,7 @@ func (c *ppClient) call(ctx context.Context, method, urlPath, token string, body
type ppSessionUser struct {
UserUID string `json:"UID"`
UserName string `json:"Name"`
Role string `json:"Role"`
BasePath string `json:"BasePath"`
}

View File

@@ -86,12 +86,15 @@ func reconcileUserBasepaths(ppDSN, originalsRoot string, mapping map[string]stri
// ACL kicks in even if the directory is created later.
}
// upload_path rides along with base_path so anything a client app
// uploads (WebDAV sync apps, PhotoPrism's own UI) lands inside the
// user's library subtree instead of the shared originals root.
res := db.Exec(`UPDATE auth_users
SET base_path = ?
SET base_path = ?, upload_path = ?
WHERE user_name = ?
AND COALESCE(base_path, '') <> ?
AND (COALESCE(base_path, '') <> ? OR COALESCE(upload_path, '') <> ?)
AND deleted_at IS NULL`,
path, username, path)
path, path, username, path, path)
if res.Error != nil {
slog.Error("user-basepath: update failed", "user", username, "err", res.Error)
continue

View File

@@ -7,10 +7,13 @@ import {
batchArchive,
batchDelete,
batchRestore,
bulkSetMarks,
removeFromHeap,
type PhotoMark,
type PhotoMarksMap,
type PpAlbum
} from '$lib/services/photoprism';
import { acceptDateAndKeep, cachedPhoto } from '$lib/services/photoActions';
import { acceptDateAndKeep, cachedPhoto, toggleFavorite } from '$lib/services/photoActions';
import { suggestDateFromPath } from '$lib/utils/suggestDateFromPath';
import { photoNameAndDir } from '$lib/types/photoprism';
import { queryClient } from '$lib/queryClient';
@@ -36,7 +39,14 @@ import {
setDetail,
markRemoved
} from '$lib/stores/bulkAction.svelte';
import { openPreview, toggleLeftSidebar, toggleRightSidebar, view } from '$lib/stores/view.svelte';
import {
closeShortcuts,
openPreview,
toggleLeftSidebar,
toggleRightSidebar,
toggleShortcuts,
view
} from '$lib/stores/view.svelte';
/**
* Optional parameters the host passes via `use:gridKeyNav={...}`.
@@ -68,8 +78,8 @@ export interface GridKeyNavParams {
* heap N (bare s adds to the currently-viewed heap), b/Tab toggles
* left sidebar, i toggles right sidebar, esc clears, ⌘Z undoes,
* ⌘A selects all visible.
* Rating + color labels are mouse-driven via the metadata sidebar — no
* keyboard shortcuts.
* 05 rating, 69 Lightroom color labels, / focuses search,
* ? opens the shortcut reference overlay.
*
* Archive / restore target a synthesized "cull target list" — in priority:
* 1. multi-selection set
@@ -377,6 +387,55 @@ export function gridKeyNav(node: HTMLElement, params: GridKeyNavParams = {}) {
await addCullTargetsToHeap(heaps[idx - 1]);
}
// ── Rating / color-label keys (Lightroom layout) ─────────────────────
// Bare 05 set the rating (0 clears; re-keying the current value also
// clears, matching the sidebar's click-to-toggle). 69 toggle the four
// Lightroom color labels. Multi-selection stamps the whole set.
const COLOR_KEYS: Record<string, string> = { '6': 'red', '7': 'yellow', '8': 'green', '9': 'blue' };
async function markCullTargets(patch: PhotoMark, label: string) {
const ids = cullTargets();
if (ids.length === 0) {
toast.message('Nothing to mark', {
description: 'Click a photo or select some first'
});
return;
}
// Optimistic cache patch — the tile badges and facet panels read
// ['marks'], so stamping it up front makes the keystroke feel instant.
const prevMap = queryClient.getQueryData<PhotoMarksMap>(['marks']) ?? {};
const next: PhotoMarksMap = { ...prevMap };
for (const id of ids) {
const merged: PhotoMark = { ...next[id], ...patch };
if (!merged.rating) delete merged.rating;
if (!merged.color) delete merged.color;
next[id] = merged;
}
queryClient.setQueryData(['marks'], next);
try {
await bulkSetMarks(ids, patch);
void queryClient.invalidateQueries({ queryKey: ['marks'] });
toast.success(ids.length === 1 ? label : `${label} · ${ids.length} photos`);
} catch (err) {
queryClient.setQueryData(['marks'], prevMap);
toast.error(err instanceof Error ? err.message : 'Mark failed');
}
}
function ratingOfFirstTarget(): number {
const ids = cullTargets();
if (ids.length === 0) return 0;
const marks = queryClient.getQueryData<PhotoMarksMap>(['marks']) ?? {};
return marks[ids[0]]?.rating ?? 0;
}
function colorOfFirstTarget(): string {
const ids = cullTargets();
if (ids.length === 0) return '';
const marks = queryClient.getQueryData<PhotoMarksMap>(['marks']) ?? {};
return marks[ids[0]]?.color ?? '';
}
async function addCullTargetsToActiveHeap() {
if (filters.section !== 'heap' || !filters.heapUid) {
toast.message('Press S then 19 to pick a heap');
@@ -396,6 +455,17 @@ export function gridKeyNav(node: HTMLElement, params: GridKeyNavParams = {}) {
const tag = (e.target as HTMLElement | null)?.tagName?.toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
// Shortcuts overlay: Esc or ? closes it; every other key is inert
// while it's up so the reference card can't trigger the actions it
// documents.
if (view.shortcutsOpen) {
if (e.key === 'Escape' || e.key === '?') {
e.preventDefault();
closeShortcuts();
}
return;
}
// Modal owns arrow / Escape / Space while it's open — it handles
// its own linear nav, close-on-Esc, and close-on-Space. Action
// keys (X/S/U/A/Z) still pass through because they target the
@@ -431,6 +501,22 @@ export function gridKeyNav(node: HTMLElement, params: GridKeyNavParams = {}) {
const meta = e.metaKey || e.ctrlKey;
const shift = e.shiftKey;
// Bare digits: rating (05, re-key toggles off) and Lightroom color
// labels (69). Runs after the S-chord so "s 3" still files to heap 3.
if (!meta && !shift && /^[0-9]$/.test(e.key)) {
e.preventDefault();
const n = parseInt(e.key, 10);
if (n <= 5) {
const value = n === 0 || ratingOfFirstTarget() === n ? 0 : n;
void markCullTargets({ rating: value }, value ? `Rated ${value}` : 'Rating cleared');
} else {
const color = COLOR_KEYS[e.key];
const value = colorOfFirstTarget() === color ? '' : color;
void markCullTargets({ color: value }, value ? `Labeled ${value}` : 'Color cleared');
}
return;
}
// Space on a focused tile opens the full-screen preview modal.
// Matches the dblclick gesture so the user has both keyboard and
// mouse paths to the same surface. `e.code === 'Space'` covers
@@ -477,6 +563,17 @@ export function gridKeyNav(node: HTMLElement, params: GridKeyNavParams = {}) {
clearSelection();
setFocused(null);
return;
case '/':
// Jump to the search box (any page that renders one tags it
// with data-search-input).
if (meta) return;
e.preventDefault();
document.querySelector<HTMLInputElement>('[data-search-input]')?.focus();
return;
case '?':
e.preventDefault();
toggleShortcuts();
return;
case 'Tab':
// Tab in the grid context = mule-image's left-sidebar toggle.
// Browsers reserve Tab for focus traversal — preventDefault
@@ -556,6 +653,12 @@ export function gridKeyNav(node: HTMLElement, params: GridKeyNavParams = {}) {
e.preventDefault();
void toggleArchive('restore');
return;
case 'f':
case 'F':
if (meta || shift) return;
e.preventDefault();
void toggleFavorite(cullTargets());
return;
case 'm':
case 'M': {
if (meta || shift) return;

View File

@@ -0,0 +1,200 @@
<!--
⌘K command palette. Jump to any section, heap, folder, or tag category,
plus a few global actions (dark mode, shortcut overlay). Data comes from
the same TanStack queries the sidebar already keeps warm (['heaps'],
['folders', …]), so opening the palette costs no extra fetches once the
app has booted. bits-ui's Command owns filtering and keyboard selection.
-->
<script lang="ts">
import { goto } from '$app/navigation';
import { Command, Dialog } from 'bits-ui';
import { createQuery } from '@tanstack/svelte-query';
import { toggleMode } from 'mode-watcher';
import {
Archive,
EyeOff,
Folder,
Image,
Keyboard,
Layers,
ListChecks,
Moon,
NotebookPen,
Tags,
Users
} from 'lucide-svelte';
import { listFolders, listHeaps, type PpAlbum, type PpFolder } from '$lib/services/photoprism';
import { isAuthenticated, userLibraryBase } from '$lib/stores/session.svelte';
import { closePalette, toggleShortcuts, view } from '$lib/stores/view.svelte';
const heapsQuery = createQuery<PpAlbum[]>(() => ({
queryKey: ['heaps'],
queryFn: listHeaps,
enabled: isAuthenticated() && view.paletteOpen
}));
const foldersQuery = createQuery<PpFolder[]>(() => ({
queryKey: ['folders', userLibraryBase()],
queryFn: listFolders,
staleTime: 30_000,
enabled: isAuthenticated() && view.paletteOpen
}));
function run(fn: () => void) {
closePalette();
fn();
}
const go = (path: string) => () => run(() => void goto(path));
interface Entry {
label: string;
icon: typeof Image;
action: () => void;
}
const SECTIONS: Entry[] = [
{ label: 'All photos', icon: Image, action: go('/') },
{ label: 'Review queue', icon: ListChecks, action: go('/review') },
{ label: 'Archive', icon: Archive, action: go('/?section=archive') },
{ label: 'Hidden', icon: EyeOff, action: go('/?section=hidden') },
{ label: 'Notes', icon: NotebookPen, action: go('/notes') },
{ label: 'Tags', icon: Tags, action: go('/tags/labels') },
{ label: 'People', icon: Users, action: go('/tags/people') },
{ label: 'Duplicates', icon: Layers, action: go('/review?tab=stacks') }
];
const ACTIONS: Entry[] = [
{ label: 'Toggle dark mode', icon: Moon, action: () => run(toggleMode) },
{ label: 'Keyboard shortcuts', icon: Keyboard, action: () => run(toggleShortcuts) }
];
// Folders can number in the hundreds; the palette lists them all and
// lets Command's fuzzy filter narrow. Sorted shallow-first so top-level
// folders surface before deep ones on an empty query.
const folderEntries = $derived(
[...(foldersQuery.data ?? [])]
.sort(
(a, b) =>
a.Path.split('/').length - b.Path.split('/').length || a.Path.localeCompare(b.Path)
)
.slice(0, 400)
);
</script>
<Dialog.Root
open={view.paletteOpen}
onOpenChange={(o) => {
if (!o) closePalette();
}}
>
<Dialog.Portal>
<Dialog.Overlay class="fixed inset-0 z-[80] bg-black/50 backdrop-blur-sm" />
<Dialog.Content
class="fixed left-1/2 top-24 z-[81] w-[min(560px,92vw)] -translate-x-1/2 overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-xl"
aria-label="Command palette"
>
<Command.Root class="flex max-h-[60vh] flex-col">
<Command.Input
class="w-full border-b border-border bg-transparent px-4 py-3 text-sm outline-none placeholder:text-muted-foreground"
placeholder="Jump to a view, heap, or folder…"
/>
<Command.List class="overflow-y-auto p-1.5">
<Command.Viewport>
<Command.Empty class="px-3 py-6 text-center text-xs text-muted-foreground">
No matches.
</Command.Empty>
<Command.Group>
<Command.GroupHeading
class="px-2 pb-1 pt-2 text-[10px] uppercase tracking-wide text-muted-foreground"
>
Go to
</Command.GroupHeading>
<Command.GroupItems>
{#each SECTIONS as s (s.label)}
<Command.Item
value={s.label}
onSelect={s.action}
class="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs data-selected:bg-accent"
>
<s.icon class="h-3.5 w-3.5 text-muted-foreground" />
{s.label}
</Command.Item>
{/each}
</Command.GroupItems>
</Command.Group>
{#if (heapsQuery.data ?? []).length > 0}
<Command.Group>
<Command.GroupHeading
class="px-2 pb-1 pt-2 text-[10px] uppercase tracking-wide text-muted-foreground"
>
Heaps
</Command.GroupHeading>
<Command.GroupItems>
{#each heapsQuery.data ?? [] as heap (heap.UID)}
<Command.Item
value={`heap ${heap.Title}`}
onSelect={go(`/?section=heap&heap=${heap.UID}`)}
class="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs data-selected:bg-accent"
>
<Layers class="h-3.5 w-3.5 text-muted-foreground" />
{heap.Title}
{#if heap.PhotoCount}
<span class="ml-auto text-[10px] text-muted-foreground">
{heap.PhotoCount}
</span>
{/if}
</Command.Item>
{/each}
</Command.GroupItems>
</Command.Group>
{/if}
{#if folderEntries.length > 0}
<Command.Group>
<Command.GroupHeading
class="px-2 pb-1 pt-2 text-[10px] uppercase tracking-wide text-muted-foreground"
>
Folders
</Command.GroupHeading>
<Command.GroupItems>
{#each folderEntries as folder (folder.Path)}
<Command.Item
value={`folder ${folder.Path}`}
onSelect={go(`/?folder=${encodeURIComponent(folder.Path)}`)}
class="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs data-selected:bg-accent"
>
<Folder class="h-3.5 w-3.5 text-muted-foreground" />
<span class="truncate">{folder.Path}</span>
</Command.Item>
{/each}
</Command.GroupItems>
</Command.Group>
{/if}
<Command.Group>
<Command.GroupHeading
class="px-2 pb-1 pt-2 text-[10px] uppercase tracking-wide text-muted-foreground"
>
Actions
</Command.GroupHeading>
<Command.GroupItems>
{#each ACTIONS as a (a.label)}
<Command.Item
value={a.label}
onSelect={a.action}
class="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs data-selected:bg-accent"
>
<a.icon class="h-3.5 w-3.5 text-muted-foreground" />
{a.label}
</Command.Item>
{/each}
</Command.GroupItems>
</Command.Group>
</Command.Viewport>
</Command.List>
</Command.Root>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>

View File

@@ -0,0 +1,120 @@
<!--
Keyboard-shortcut reference overlay, opened with `?` (and the toolbar
help affordance). Read-only: gridKeyNav swallows every key except
Esc / ? while it's up, so nothing here can fire the actions it lists.
-->
<script lang="ts">
import { closeShortcuts, view } from '$lib/stores/view.svelte';
import { X } from 'lucide-svelte';
interface Row {
keys: string[];
desc: string;
}
interface Group {
title: string;
rows: Row[];
}
const GROUPS: Group[] = [
{
title: 'Navigate',
rows: [
{ keys: ['↑', '↓', '←', '→'], desc: 'Move focus in the grid' },
{ keys: ['Shift', '+', 'Arrows'], desc: 'Extend selection' },
{ keys: ['Space'], desc: 'Open / close preview' },
{ keys: ['Esc'], desc: 'Collapse selection, then clear' },
{ keys: ['/'], desc: 'Focus search' },
{ keys: ['⌘', 'A'], desc: 'Select all visible' },
{ keys: ['⌘', 'K'], desc: 'Command palette' }
]
},
{
title: 'Rate & label',
rows: [
{ keys: ['1', '…', '5'], desc: 'Set rating (re-key to clear)' },
{ keys: ['0'], desc: 'Clear rating' },
{ keys: ['6', '7', '8', '9'], desc: 'Color label: red / yellow / green / blue' },
{ keys: ['F'], desc: 'Toggle favorite' }
]
},
{
title: 'Act',
rows: [
{ keys: ['X'], desc: 'Archive (Delete in Archive view)' },
{ keys: ['U'], desc: 'Restore from archive' },
{ keys: ['S'], desc: 'Keep (review) · add to heap' },
{ keys: ['S', 'then', '19'], desc: 'Add to heap N' },
{ keys: ['A'], desc: 'Accept date & keep (EXIF review)' },
{ keys: ['M'], desc: 'Move to folder' },
{ keys: ['⌘', 'Z'], desc: 'Undo last action' }
]
},
{
title: 'Panels',
rows: [
{ keys: ['B'], desc: 'Toggle left sidebar' },
{ keys: ['Tab'], desc: 'Toggle left sidebar' },
{ keys: ['I'], desc: 'Toggle info sidebar' },
{ keys: ['?'], desc: 'This overlay' }
]
}
];
</script>
{#if view.shortcutsOpen}
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div
class="fixed inset-0 z-[70] flex items-center justify-center bg-black/50 backdrop-blur-sm"
onclick={(e) => {
if (e.target === e.currentTarget) closeShortcuts();
}}
>
<div
role="dialog"
aria-modal="true"
aria-label="Keyboard shortcuts"
class="max-h-[85vh] w-[min(680px,92vw)] overflow-y-auto rounded-lg border border-border bg-popover p-5 text-popover-foreground shadow-xl"
>
<div class="mb-4 flex items-center justify-between">
<h2 class="text-sm font-semibold">Keyboard shortcuts</h2>
<button
class="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
onclick={closeShortcuts}
aria-label="Close"
>
<X class="h-4 w-4" />
</button>
</div>
<div class="grid gap-x-8 gap-y-4 sm:grid-cols-2">
{#each GROUPS as group (group.title)}
<section>
<h3 class="mb-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{group.title}
</h3>
<dl class="space-y-1">
{#each group.rows as row (row.desc)}
<div class="flex items-center justify-between gap-3 text-xs">
<dt class="text-muted-foreground">{row.desc}</dt>
<dd class="flex shrink-0 items-center gap-0.5">
{#each row.keys as k (k)}
{#if k === 'then' || k === '+' || k === '…'}
<span class="px-0.5 text-[10px] text-muted-foreground">{k}</span>
{:else}
<kbd
class="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] leading-none"
>
{k}
</kbd>
{/if}
{/each}
</dd>
</div>
{/each}
</dl>
</section>
{/each}
</div>
</div>
</div>
{/if}

View File

@@ -101,6 +101,90 @@
setFocused(next);
setAnchor(next);
}
// ── Zoom & pan ───────────────────────────────────────────────────────
// Wheel zooms around the cursor, double-click toggles 1↔2.5, drag pans
// while zoomed. Transform lives on a wrapper so the LQIP layer and the
// sharp image scale together. Resets on photo change. Past 1.25× the
// sharp <img> switches to fit_2048 so zoomed pixels stay crisp.
const MAX_ZOOM = 6;
let zoom = $state(1);
let tx = $state(0);
let ty = $state(0);
let zoomHost = $state<HTMLElement | undefined>();
let panning = $state(false);
let lastX = 0;
let lastY = 0;
$effect(() => {
void uid;
zoom = 1;
tx = 0;
ty = 0;
});
function applyZoom(next: number, clientX: number, clientY: number) {
if (!zoomHost) return;
const clamped = Math.min(MAX_ZOOM, Math.max(1, next));
if (clamped === zoom) return;
// Keep the point under the cursor fixed: translate offsets are in
// post-scale pixels around the container centre.
const rect = zoomHost.getBoundingClientRect();
const cx = clientX - rect.left - rect.width / 2;
const cy = clientY - rect.top - rect.height / 2;
const s = clamped / zoom;
tx = cx + (tx - cx) * s;
ty = cy + (ty - cy) * s;
zoom = clamped;
if (zoom === 1) {
tx = 0;
ty = 0;
}
}
function onWheel(e: WheelEvent) {
e.preventDefault();
applyZoom(zoom * Math.exp(-e.deltaY * 0.0018), e.clientX, e.clientY);
}
/** Svelte marks wheel handlers passive; zooming needs preventDefault,
* so the listener is attached manually as non-passive. */
function wheelZoom(node: HTMLElement) {
node.addEventListener('wheel', onWheel, { passive: false });
return {
destroy() {
node.removeEventListener('wheel', onWheel);
}
};
}
function onDblClickZoom(e: MouseEvent) {
if (zoom > 1) {
zoom = 1;
tx = 0;
ty = 0;
} else {
applyZoom(2.5, e.clientX, e.clientY);
}
}
function onPointerDown(e: PointerEvent) {
if (zoom === 1) return;
panning = true;
lastX = e.clientX;
lastY = e.clientY;
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
}
function onPointerMove(e: PointerEvent) {
if (!panning) return;
tx += e.clientX - lastX;
ty += e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
}
function onPointerUp() {
panning = false;
}
</script>
<div class="relative flex h-full w-full items-center justify-center bg-black/40 p-4">
@@ -145,30 +229,61 @@
photoQuery.data.OriginalName ??
pf.Name ??
(isVideo(photoQuery.data) ? 'Video' : 'Photo')}
{#if pf.Width && pf.Height}
<!-- LQIP layer: the same URL the grid loaded, blurred to mask
the tile_*'s square center-crop against the sharp image's
true aspect. Sized via aspect-ratio + max-* + m-auto so it
lands in the exact same bounding box as the sharp <img>
beside it (object-contain semantics, but expressible on a
positioned element). Paints from the HTTP cache the moment
the modal opens. -->
<img
src={thumbSrc(pf.Hash, view.thumbnailSize)}
srcset={thumbSrcSet(pf.Hash, view.thumbnailSize)}
alt=""
aria-hidden="true"
class="pointer-events-none absolute inset-0 m-auto max-h-full max-w-full rounded-md object-cover blur-2xl"
style="aspect-ratio: {pf.Width} / {pf.Height};"
/>
{/if}
<img
src={thumbUrl(pf.Hash, 'fit_1280')}
alt={altText}
fetchpriority="high"
decoding="async"
class="relative max-h-full max-w-full rounded-md object-contain shadow-2xl"
/>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={zoomHost}
use:wheelZoom
ondblclick={onDblClickZoom}
onpointerdown={onPointerDown}
onpointermove={onPointerMove}
onpointerup={onPointerUp}
onpointercancel={onPointerUp}
class="relative flex h-full w-full items-center justify-center overflow-hidden {zoom > 1
? panning
? 'cursor-grabbing'
: 'cursor-grab'
: 'cursor-zoom-in'}"
>
<div
class="relative flex h-full w-full items-center justify-center"
class:transition-transform={!panning}
class:duration-150={!panning}
style="transform: translate({tx}px, {ty}px) scale({zoom});"
>
{#if pf.Width && pf.Height}
<!-- LQIP layer: the same URL the grid loaded, blurred to mask
the tile_*'s square center-crop against the sharp image's
true aspect. Sized via aspect-ratio + max-* + m-auto so it
lands in the exact same bounding box as the sharp <img>
beside it (object-contain semantics, but expressible on a
positioned element). Paints from the HTTP cache the moment
the modal opens. -->
<img
src={thumbSrc(pf.Hash, view.thumbnailSize)}
srcset={thumbSrcSet(pf.Hash, view.thumbnailSize)}
alt=""
aria-hidden="true"
class="pointer-events-none absolute inset-0 m-auto max-h-full max-w-full rounded-md object-cover blur-2xl"
style="aspect-ratio: {pf.Width} / {pf.Height};"
/>
{/if}
<img
src={thumbUrl(pf.Hash, zoom > 1.25 ? 'fit_2048' : 'fit_1280')}
alt={altText}
fetchpriority="high"
decoding="async"
draggable="false"
class="relative max-h-full max-w-full select-none rounded-md object-contain shadow-2xl"
/>
</div>
{#if zoom > 1}
<span
class="absolute bottom-2 left-1/2 -translate-x-1/2 rounded bg-background/80 px-2 py-0.5 text-[11px] text-foreground"
>
{Math.round(zoom * 100)}% · double-click to reset
</span>
{/if}
</div>
{/if}
{/if}
</div>

View File

@@ -13,10 +13,12 @@
Aperture,
ArrowUpRight,
Calendar,
Copy,
File,
Folder,
Globe,
HardDrive,
Heart,
ImageIcon,
Loader2,
MapPin,
@@ -37,12 +39,14 @@
type UpdatePhotoBody
} from '$lib/services/photoprism';
import { invalidateFacets } from '$lib/services/bulk';
import { toggleFavorite } from '$lib/services/photoActions';
import { startBulk, doneBulk, failBulk } from '$lib/stores/bulkAction.svelte';
import { isAuthenticated } from '$lib/stores/session.svelte';
import { push as pushUndo } from '$lib/stores/undo.svelte';
import { getMetadataSectionOpen, setMetadataSection } from '$lib/stores/view.svelte';
import { photoNameAndDir, primaryFile, type PpPhoto } from '$lib/types/photoprism';
import { navigateToFolder, navigateToTag } from '$lib/stores/filters.svelte';
import { navigateToFolder, navigateToTag, setSearch, setSection } from '$lib/stores/filters.svelte';
import { goto } from '$app/navigation';
import { COLOR_SWATCHES } from '$lib/utils/tagGroups';
import { countryName } from '$lib/utils/countries';
import { suggestDateFromPath } from '$lib/utils/suggestDateFromPath';
@@ -307,6 +311,36 @@
const joined = `${make} ${model}`.trim();
return joined && joined !== 'Unknown' ? joined : '';
}
/** Quote for PhotoPrism's q= DSL — mirrors filters.svelte's quoteIfNeeded,
* duplicated here since that helper isn't exported. */
function quoteTerm(v: string): string {
return /^[A-Za-z0-9_-]+$/.test(v) ? v : `"${v.replace(/"/g, '\\"')}"`;
}
/** Jump to the timeline filtered by a raw DSL term (camera:/lens:) — the
* q-DSL escape hatch from the toolbar search box, triggered by click
* instead of typing. */
async function jumpToSearch(term: string): Promise<void> {
setSection('all-photos');
setSearch(term);
await goto('/', { keepFocus: true, noScroll: true });
}
async function copyExif(): Promise<void> {
const lines = [
cameraStr && `Camera: ${cameraStr}`,
lensStr && lensStr !== cameraStr && `Lens: ${lensStr}`,
exposureParts.fnum && `Aperture: ${exposureParts.fnum}`,
exposureParts.exp && `Shutter: ${exposureParts.exp}`,
exposureParts.iso && exposureParts.iso,
exposureParts.focal && `Focal length: ${exposureParts.focal}`,
photo.TakenAt && `Taken: ${photo.TakenAt}`
].filter(Boolean);
if (lines.length === 0) {
toast.message('No EXIF to copy');
return;
}
await navigator.clipboard.writeText(lines.join('\n'));
toast.success('EXIF copied');
}
function formatExposureParts(p: PpPhoto): { iso: string; fnum: string; focal: string; exp: string } {
return {
iso: p.Iso ? `ISO ${p.Iso}` : '',
@@ -501,6 +535,19 @@
<Star class="h-3.5 w-3.5" fill={currentRating >= n ? 'currentColor' : 'none'} />
</button>
{/each}
<!-- PhotoPrism's native favorite — syncs to mobile gallery apps. -->
<button
type="button"
class="ml-2 p-0.5 transition-colors {photo.Favorite
? 'text-red-500'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => void toggleFavorite([photo.UID])}
title={photo.Favorite ? 'Remove from favorites (f)' : 'Add to favorites (f)'}
aria-pressed={photo.Favorite ?? false}
aria-label="Favorite"
>
<Heart class="h-3.5 w-3.5" fill={photo.Favorite ? 'currentColor' : 'none'} />
</button>
</div>
</div>
@@ -641,20 +688,51 @@
ontoggle={(e) => setMetadataSection('file', e.currentTarget.open)}
>
<summary
class="cursor-pointer px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground"
class="flex cursor-pointer items-center justify-between px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground"
>
<span class="inline-flex items-center gap-1">
<ImageIcon class="h-3 w-3" /> File
</span>
<button
type="button"
class="normal-case text-muted-foreground hover:text-foreground"
onclick={(e) => {
e.preventDefault();
e.stopPropagation();
void copyExif();
}}
title="Copy EXIF summary"
aria-label="Copy EXIF summary"
>
<Copy class="h-3 w-3" />
</button>
</summary>
<dl class="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 p-2 pt-1 text-[10px]">
{#if cameraStr}
<dt class="text-muted-foreground">Camera</dt>
<dd class="text-foreground/80">{cameraStr}</dd>
<dd class="min-w-0">
<button
type="button"
class="truncate text-left text-foreground/80 hover:text-foreground hover:underline"
onclick={() => void jumpToSearch(`camera:${quoteTerm(cameraStr)}`)}
title={`View other photos taken with ${cameraStr}`}
>
{cameraStr}
</button>
</dd>
{/if}
{#if lensStr && lensStr !== cameraStr}
<dt class="text-muted-foreground">Lens</dt>
<dd class="text-foreground/80">{lensStr}</dd>
<dd class="min-w-0">
<button
type="button"
class="truncate text-left text-foreground/80 hover:text-foreground hover:underline"
onclick={() => void jumpToSearch(`lens:${quoteTerm(lensStr)}`)}
title={`View other photos taken with ${lensStr}`}
>
{lensStr}
</button>
</dd>
{/if}
{#if exposureParts.fnum || exposureParts.exp || exposureParts.iso || exposureParts.focal}
<dt class="text-muted-foreground">Exposure</dt>

View File

@@ -17,8 +17,9 @@
import { view } from "$lib/stores/view.svelte";
import { isVideo, primaryFile, type PpPhoto } from "$lib/types/photoprism";
import { bulkPhotoStates } from "$lib/stores/bulkAction.svelte";
import { toggleFavorite } from "$lib/services/photoActions";
import { fade } from "svelte/transition";
import { Loader2, Check, X } from "lucide-svelte";
import { Loader2, Check, Heart, X } from "lucide-svelte";
interface Props {
photo: PpPhoto;
@@ -191,4 +192,28 @@
>
{/if}
</button>
<!--
Favorite heart — a *sibling* of the tile button (nested buttons are
invalid HTML and break click semantics). Filled + always visible when
favorited; otherwise fades in on hover. Mirrors the `f` shortcut.
-->
<button
type="button"
class="absolute bottom-1.5 right-1.5 z-10 rounded-full bg-background/70 p-1 backdrop-blur transition-opacity {photo.Favorite
? 'opacity-100'
: 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}"
onclick={(e) => {
e.stopPropagation();
void toggleFavorite([photo.UID]);
}}
ondblclick={(e) => e.stopPropagation()}
title={photo.Favorite ? "Remove from favorites (f)" : "Add to favorites (f)"}
aria-pressed={photo.Favorite ?? false}
aria-label="Favorite"
>
<Heart
class="h-3.5 w-3.5 {photo.Favorite ? 'text-red-500' : 'text-foreground/80'}"
fill={photo.Favorite ? "currentColor" : "none"}
/>
</button>
</div>

View File

@@ -9,7 +9,12 @@ export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 1
retry: 1,
// The indexer WebSocket (stores/indexer.svelte.ts) already
// invalidates ['photos'] and friends on live changes, so a
// window-focus refetch only adds a redundant full-timeline
// re-render (visible flash) every time the tab regains focus.
refetchOnWindowFocus: false
}
}
});

View File

@@ -19,6 +19,8 @@ import {
batchArchive,
batchRestore,
buildTakenAtPatch,
likePhoto,
unlikePhoto,
updatePhoto
} from './photoprism';
import { queryClient } from '$lib/queryClient';
@@ -121,6 +123,70 @@ export async function acceptDateAndKeep(uids: string[]): Promise<void> {
toast.success(`Kept ${uids.length}`, { id: tid });
}
/** Patch `Favorite` on every cached copy of the uids (timeline pages,
* per-photo detail) so hearts flip instantly without a refetch. */
function patchFavoriteCaches(uids: string[], value: boolean): void {
const target = new Set(uids);
const lists = queryClient.getQueriesData({ queryKey: ['photos'] });
for (const [key, data] of lists) {
if (!data) continue;
if (Array.isArray(data)) {
queryClient.setQueryData(
key,
(data as PpPhoto[]).map((p) => (target.has(p.UID) ? { ...p, Favorite: value } : p))
);
continue;
}
const pages = (data as { pages?: PpPhoto[][] }).pages;
if (!Array.isArray(pages)) continue;
queryClient.setQueryData(key, {
...(data as object),
pages: pages.map((pg) =>
pg.map((p) => (target.has(p.UID) ? { ...p, Favorite: value } : p))
)
});
}
for (const uid of uids) {
const p = queryClient.getQueryData<PpPhoto>(['photo', uid]);
if (p) queryClient.setQueryData(['photo', uid], { ...p, Favorite: value });
}
}
/**
* Toggle PhotoPrism's native favorite flag on a set of photos. Target
* state comes from the first uid (mixed selections converge). Optimistic
* cache flip with rollback; undo re-toggles.
*/
export async function toggleFavorite(uids: string[]): Promise<void> {
if (uids.length === 0) {
toast.message('Nothing to favorite', {
description: 'Click a photo or select some first'
});
return;
}
const value = !(cachedPhoto(uids[0])?.Favorite ?? false);
patchFavoriteCaches(uids, value);
const { errors } = await batchEdit(uids, (id) => (value ? likePhoto(id) : unlikePhoto(id)));
if (errors.length) {
patchFavoriteCaches(uids, !value);
toast.error(`Favorite failed on ${errors.length}`, { description: errors[0].message });
return;
}
toast.success(
value
? uids.length === 1
? 'Added to favorites'
: `Favorited ${uids.length}`
: uids.length === 1
? 'Removed from favorites'
: `Unfavorited ${uids.length}`
);
pushUndo(value ? `Favorited ${uids.length}` : `Unfavorited ${uids.length}`, async () => {
patchFavoriteCaches(uids, !value);
await batchEdit(uids, (id) => (value ? unlikePhoto(id) : likePhoto(id)));
});
}
/**
* Archive photos. Reversible via the undo stack (Restore on ⌘Z).
*/

View File

@@ -1050,6 +1050,18 @@ export async function moveFolder(rel: string, targetParent: string): Promise<Fol
}) as Promise<FolderMoveResult>;
}
// ── Favorites ────────────────────────────────────────────────────────────────
// PhotoPrism's native favorite flag — unlike marks, this syncs to any
// PhotoPrism-compatible client app.
export async function likePhoto(uid: string): Promise<void> {
await http.post(`/photos/${encodeURIComponent(uid)}/like`);
}
export async function unlikePhoto(uid: string): Promise<void> {
await http.delete(`/photos/${encodeURIComponent(uid)}/like`);
}
// ── Photo marks (rating + color) ─────────────────────────────────────────────
// PhotoPrism's PUT silently drops Rating and Color (they're auto-computed
// internal fields). We store them in mule-sidecar instead.

View File

@@ -41,6 +41,25 @@ export function isTagCategory(v: unknown): v is TagCategory {
);
}
export type SortOrder = 'newest' | 'oldest' | 'added' | 'name';
export const SORT_ORDERS: readonly SortOrder[] = ['newest', 'oldest', 'added', 'name'] as const;
export const SORT_LABELS: Record<SortOrder, string> = {
newest: 'Newest first',
oldest: 'Oldest first',
added: 'Recently added',
name: 'File name'
};
/** Media-type chip values → PhotoPrism boolean q-DSL filters. */
export type MediaType = 'photo' | 'video' | 'raw' | 'live';
export const MEDIA_TYPES: readonly MediaType[] = ['photo', 'video', 'raw', 'live'] as const;
export const MEDIA_TYPE_LABELS: Record<MediaType, string> = {
photo: 'Photos',
video: 'Videos',
raw: 'RAW',
live: 'Live'
};
export interface FilterState {
section: Section;
/** Heap UID, used when section === 'heap'. */
@@ -49,6 +68,14 @@ export interface FilterState {
folderPath: string | null;
/** Free-form search text, ANDed with section-derived terms. */
search: string;
/** Timeline sort order. Maps straight onto PhotoPrism's `order` param. */
sort: SortOrder;
/** Media-type chip; null = any. */
mediaType: MediaType | null;
/** Year chip; null = any. Compiles to `year:<n>`. */
year: number | null;
/** Favorites-only chip. Compiles to `favorite:true`. */
favorite: boolean;
/**
* Active tag-browser category and selected value. Set by the
* `/tags/[category]/[[value]]` route on navigation. Labels/keywords
@@ -68,10 +95,42 @@ export const filters = $state<FilterState>({
heapUid: null,
folderPath: '/',
search: '',
sort: 'newest',
mediaType: null,
year: null,
favorite: false,
tagCategory: null,
tagValue: null
});
export function setSort(sort: SortOrder): void {
filters.sort = sort;
}
export function setMediaType(t: MediaType | null): void {
filters.mediaType = t;
}
export function setYear(y: number | null): void {
filters.year = y;
}
export function setFavorite(on: boolean): void {
filters.favorite = on;
}
/** True when any toolbar chip narrows the view (excludes sort — a sort
* isn't a filter). Drives the "Clear" affordance. */
export function chipsActive(f: FilterState = filters): boolean {
return f.mediaType !== null || f.year !== null || f.favorite;
}
export function clearChips(): void {
filters.mediaType = null;
filters.year = null;
filters.favorite = false;
}
export function setSection(section: Section, heapUid: string | null = null): void {
filters.section = section;
filters.heapUid = section === 'heap' ? heapUid : null;
@@ -250,7 +309,19 @@ export function filtersToQ(f: FilterState = filters): string {
parts.push(`country:${quoteIfNeeded(f.tagValue)}`);
}
}
if (f.search) parts.push(quoteIfNeeded(f.search));
// Toolbar chips. PhotoPrism's boolean media filters (`video:true`,
// `photo:true`, …) are the documented DSL forms; `year:` and
// `favorite:` are plain filters.
if (f.mediaType) parts.push(`${f.mediaType}:true`);
if (f.year) parts.push(`year:${f.year}`);
if (f.favorite) parts.push('favorite:true');
// `f.search` is the raw-DSL escape hatch (toolbar cheat-sheet examples
// like `label:dog`, `taken:2024`) as well as plain free text. Only
// quote it when it has no `:` — a colon means the user (or a
// jump-to-search link) already wrote a structured term, and wrapping
// the whole thing in quotes would turn `camera:iPhone` into a literal
// phrase search for the text "camera:iPhone" instead of the operator.
if (f.search) parts.push(f.search.includes(':') ? f.search : quoteIfNeeded(f.search));
return parts.join(' ');
}
@@ -272,11 +343,22 @@ export function parseUrlParams(params: URLSearchParams): Partial<FilterState> {
!params.has('q');
const folderRaw = params.get('folder');
const folderPath = folderRaw !== null ? folderRaw : bare ? '/' : null;
const sortRaw = params.get('sort');
const typeRaw = params.get('type');
const yearRaw = params.get('year');
return {
section,
heapUid: params.get('heap'),
folderPath,
search: params.get('q') ?? ''
search: params.get('q') ?? '',
sort: (SORT_ORDERS as readonly string[]).includes(sortRaw ?? '')
? (sortRaw as SortOrder)
: 'newest',
mediaType: (MEDIA_TYPES as readonly string[]).includes(typeRaw ?? '')
? (typeRaw as MediaType)
: null,
year: yearRaw && /^\d{4}$/.test(yearRaw) ? parseInt(yearRaw, 10) : null,
favorite: params.get('fav') === '1'
};
}
@@ -288,5 +370,9 @@ export function filtersToUrlParams(f: FilterState = filters): URLSearchParams {
if (f.heapUid) params.set('heap', f.heapUid);
if (f.folderPath) params.set('folder', f.folderPath);
if (f.search) params.set('q', f.search);
if (f.sort !== 'newest') params.set('sort', f.sort);
if (f.mediaType) params.set('type', f.mediaType);
if (f.year) params.set('year', String(f.year));
if (f.favorite) params.set('fav', '1');
return params;
}

View File

@@ -81,6 +81,10 @@ export const view = $state<{
* persisted — a refresh always returns to the grid.
*/
previewOpen: boolean;
/** Ephemeral: true while the keyboard-shortcuts overlay is open. */
shortcutsOpen: boolean;
/** Ephemeral: true while the ⌘K command palette is open. */
paletteOpen: boolean;
metadataSections: Record<string, boolean>;
}>({
rightSidebarCollapsed: initial.rightSidebarCollapsed ?? false,
@@ -107,6 +111,8 @@ export const view = $state<{
),
tagsBrowserCollapsed: initial.tagsBrowserCollapsed ?? false,
previewOpen: false,
shortcutsOpen: false,
paletteOpen: false,
metadataSections:
initial.metadataSections && typeof initial.metadataSections === 'object'
? { ...initial.metadataSections }
@@ -164,6 +170,22 @@ export function togglePreview(): void {
view.previewOpen = !view.previewOpen;
}
export function toggleShortcuts(): void {
view.shortcutsOpen = !view.shortcutsOpen;
}
export function closeShortcuts(): void {
view.shortcutsOpen = false;
}
export function togglePalette(): void {
view.paletteOpen = !view.paletteOpen;
}
export function closePalette(): void {
view.paletteOpen = false;
}
export function setThumbnailSize(size: ThumbnailSize): void {
view.thumbnailSize = size;
persist();

View File

@@ -130,6 +130,7 @@ export interface PpPhoto {
Height?: number;
Rating?: number;
Color?: string | number;
Favorite?: boolean;
Archived?: boolean;
Files?: PpFile[];
Lat?: number;

View File

@@ -20,6 +20,9 @@
import AnimatedMule from '$lib/components/mule/AnimatedMule.svelte';
import PreviewModal from '$lib/components/preview/PreviewModal.svelte';
import MoveToFolderDialog from '$lib/components/layout/MoveToFolderDialog.svelte';
import ShortcutsDialog from '$lib/components/layout/ShortcutsDialog.svelte';
import CommandPalette from '$lib/components/layout/CommandPalette.svelte';
import { togglePalette } from '$lib/stores/view.svelte';
let { children } = $props();
@@ -58,8 +61,18 @@
else stopIndexerWatch();
});
// ⌘K lives at the window level (not gridKeyNav) so the palette opens
// from any route and even while a form field holds focus.
function onGlobalKey(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
e.preventDefault();
togglePalette();
}
}
</script>
<svelte:window onkeydown={onGlobalKey} />
<svelte:head>
<title>Mulimage</title>
</svelte:head>
@@ -122,6 +135,10 @@
store. Opened from the heap/folder kebabs, the BulkActionBar
button, and the `m` shortcut — all through openMove(). -->
<MoveToFolderDialog />
<!-- Keyboard-shortcut reference, toggled by `?` via gridKeyNav. -->
<ShortcutsDialog />
<!-- ⌘K palette — jump to sections/heaps/folders + global actions. -->
<CommandPalette />
{:else}
{@render children?.()}
{/if}

View File

@@ -17,14 +17,26 @@
type PpAlbum,
} from "$lib/services/photoprism";
import {
chipsActive,
clearChips,
consumePendingFocus,
filters,
filtersToQ,
filtersToUrlParams,
MEDIA_TYPE_LABELS,
MEDIA_TYPES,
parseUrlParams,
setFavorite,
setMediaType,
setSearch,
setSection,
setSort,
setYear,
SORT_LABELS,
SORT_ORDERS,
type MediaType,
type PendingFocus,
type SortOrder,
} from "$lib/stores/filters.svelte";
import { isAuthenticated } from "$lib/stores/session.svelte";
import { untrack } from "svelte";
@@ -81,6 +93,10 @@
if (next.heapUid !== undefined) filters.heapUid = next.heapUid;
if (next.folderPath !== undefined) filters.folderPath = next.folderPath;
if (next.search !== undefined) filters.search = next.search;
if (next.sort !== undefined) filters.sort = next.sort;
if (next.mediaType !== undefined) filters.mediaType = next.mediaType;
if (next.year !== undefined) filters.year = next.year;
if (next.favorite !== undefined) filters.favorite = next.favorite;
});
// When the store changes from in-app actions (left-sidebar nav, search
@@ -182,15 +198,20 @@
"photos",
"q",
filtersToQ(filters),
{ count: PHOTOS_PAGE_SIZE, anchor: anchor?.takenAt ?? null },
{
count: PHOTOS_PAGE_SIZE,
anchor: anchor?.takenAt ?? null,
sort: filters.sort,
},
],
queryFn: ({ pageParam }) => {
const offset = pageParam as number;
const baseQ = filtersToQ(filters);
// Page 0 + anchor → load a window around the anchor's date.
// Subsequent pages aren't reachable in anchor mode (see
// getNextPageParam).
if (offset === 0 && anchor?.takenAt) {
// getNextPageParam). Anchor windows assume chronological order,
// so any non-default sort falls back to plain paging.
if (offset === 0 && anchor?.takenAt && filters.sort === "newest") {
return listPhotosAround({
q: baseQ,
takenAt: anchor.takenAt,
@@ -203,7 +224,7 @@
q: baseQ,
count: PHOTOS_PAGE_SIZE,
offset,
order: "newest",
order: filters.sort,
merged: true,
});
},
@@ -222,7 +243,7 @@
// photos exceeding the page size keep the cursor at the same
// value). To "see more," the user clears the anchor by
// navigating fresh.
if (anchor?.takenAt) return undefined;
if (anchor?.takenAt && filters.sort === "newest") return undefined;
return pages.length * PHOTOS_PAGE_SIZE;
},
enabled: isAuthenticated(),
@@ -800,6 +821,16 @@
setSearch(searchDraft.trim());
}
// Toolbar chips: years from the current year back to 1990 — static
// range keeps it dependency-free; PhotoPrism just returns an empty
// page for years with no photos.
const CHIP_YEARS = Array.from(
{ length: new Date().getFullYear() - 1989 },
(_, i) => new Date().getFullYear() - i,
);
const CHIP_SELECT_CLASS =
"rounded border border-input bg-background px-1.5 py-0.5 text-[11px] text-foreground shadow-sm focus:outline-none focus:ring-1 focus:ring-ring";
// PhotoPrism's q-DSL is non-obvious; surfacing 4 working examples on
// focus turns the placeholder hint into a clickable cheat-sheet.
const SEARCH_EXAMPLES = [
@@ -843,6 +874,7 @@
<form class="relative flex items-center gap-1" onsubmit={onSearchSubmit}>
<input
type="search"
data-search-input
placeholder={'Search · label:website / "vacation"'}
class="w-56 rounded border border-input bg-background px-2 py-0.5 text-xs shadow-sm focus:outline-none focus:ring-2 focus:ring-ring"
bind:value={searchDraft}
@@ -898,6 +930,68 @@
{/if}
</form>
<!-- Filter chips: sort / media type / year / favorites. Compile into
the same q-DSL the search box feeds, so they stack with search,
folders, and sections. URL-persisted for shareable views. -->
<div class="flex shrink-0 items-center gap-1" role="group" aria-label="Filters">
<select
class={CHIP_SELECT_CLASS}
value={filters.sort}
onchange={(e) => setSort(e.currentTarget.value as SortOrder)}
title="Sort order"
aria-label="Sort order"
>
{#each SORT_ORDERS as s (s)}
<option value={s}>{SORT_LABELS[s]}</option>
{/each}
</select>
<select
class={CHIP_SELECT_CLASS}
value={filters.mediaType ?? ""}
onchange={(e) => setMediaType((e.currentTarget.value || null) as MediaType | null)}
title="Media type"
aria-label="Media type"
>
<option value="">Any type</option>
{#each MEDIA_TYPES as t (t)}
<option value={t}>{MEDIA_TYPE_LABELS[t]}</option>
{/each}
</select>
<select
class={CHIP_SELECT_CLASS}
value={filters.year ? String(filters.year) : ""}
onchange={(e) => setYear(e.currentTarget.value ? parseInt(e.currentTarget.value, 10) : null)}
title="Year"
aria-label="Year"
>
<option value="">Any year</option>
{#each CHIP_YEARS as y (y)}
<option value={String(y)}>{y}</option>
{/each}
</select>
<button
type="button"
class="rounded border px-1.5 py-0.5 text-[11px] transition-colors {filters.favorite
? 'border-red-400 bg-red-500/10 text-red-500'
: 'border-input text-muted-foreground hover:bg-accent'}"
aria-pressed={filters.favorite}
onclick={() => setFavorite(!filters.favorite)}
title="Favorites only (f toggles a photo's favorite)"
>
♥ Favorites
</button>
{#if chipsActive(filters)}
<button
type="button"
class="rounded px-1.5 py-0.5 text-[11px] text-muted-foreground underline-offset-2 hover:underline"
onclick={clearChips}
title="Clear type / year / favorites filters"
>
Clear
</button>
{/if}
</div>
{#snippet trailing()}
<!-- Thumbnail size — five steps mirroring mule-image's XS/S/M/L/XL.
Persisted to localStorage via view.svelte.ts. -->

View File

@@ -82,6 +82,10 @@
heapUid: null,
folderPath: null,
search: '',
sort: 'newest',
mediaType: null,
year: null,
favorite: false,
tagCategory: category,
tagValue: selectedValue
})