From 1c7b19f00945b43d91a59b8a3d28eaa0e49559ac Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Sun, 30 Aug 2026 14:04:49 +0200 Subject: [PATCH 01/19] feat(webdav): thumbnails through a Tika server Every file the built-in converters cannot render goes to /unpack/thumbnail (Tika 4.1) and comes back with the image Tika marks as its thumbnail. --- services/webdav/README.md | 4 +- services/webdav/pkg/config/config.go | 3 + services/webdav/pkg/preprocessor/errors.go | 1 + .../webdav/pkg/preprocessor/preprocessor.go | 47 ++++++-- services/webdav/pkg/preprocessor/tika.go | 99 +++++++++++++++ services/webdav/pkg/preprocessor/tika_test.go | 114 ++++++++++++++++++ services/webdav/pkg/service/v0/service.go | 5 +- .../pkg/service/v0/thumbnail_errors_test.go | 39 ++++++ services/webdav/pkg/thumbnail/tika.go | 61 ++++++++++ services/webdav/pkg/thumbnail/tika_test.go | 37 ++++++ services/webdav/pkg/thumbnail/typemapping.go | 4 +- .../webdav/pkg/thumbnail/typemapping_test.go | 4 + .../pkg/thumbnail/workflow/format_test.go | 18 +++ .../webdav/pkg/thumbnail/workflow/workflow.go | 114 +++++++++++++++--- 14 files changed, 521 insertions(+), 29 deletions(-) create mode 100644 services/webdav/pkg/preprocessor/tika.go create mode 100644 services/webdav/pkg/preprocessor/tika_test.go create mode 100644 services/webdav/pkg/service/v0/thumbnail_errors_test.go create mode 100644 services/webdav/pkg/thumbnail/tika.go create mode 100644 services/webdav/pkg/thumbnail/tika_test.go create mode 100644 services/webdav/pkg/thumbnail/workflow/format_test.go diff --git a/services/webdav/README.md b/services/webdav/README.md index a3d089ea7f..cc479b900c 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,6 +10,8 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.1 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. + Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. #### Thumbnail Query String Parameters @@ -76,7 +78,7 @@ Three settings say what is made of what. Each one is merged onto the built-in de Reading them as a chain: a source type is mapped to the type its thumbnail is returned in, and that type is asked for by the name the generator knows it under. An icon becomes `image/png`, which the generator is asked for as `format(png)`. A type nobody mapped becomes a JPEG, and so does a mapping onto a type this service has no format name for: what a generator behind the URL really writes is its own business, and a wrong guess here must not keep the service from starting. -The defaults return `image/png` for png and icon sources, keep `image/gif` for a gif and return `image/jpeg` for everything else, so a client must read the response's `Content-Type` instead of assuming the type it got before. +The defaults return `image/png` for png, icon and windows binary sources, keep `image/gif` for a gif and return `image/jpeg` for everything else, so a client must read the response's `Content-Type` instead of assuming the type it got before. Previews can be switched off entirely with `OC_DISABLE_PREVIEWS`. Search keeps working, every thumbnail path answers `404`, and nothing here is read or checked: a typo in the resolutions, the cache backend or the type mapping surfaces when previews are switched back on, not before. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index c191486f47..4eee54d7ee 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -28,6 +28,9 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` + TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.1 or newer with the thumbnail preset active in its configuration." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. Empty means all types that are not handled directly. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` + Context context.Context `yaml:"-"` } diff --git a/services/webdav/pkg/preprocessor/errors.go b/services/webdav/pkg/preprocessor/errors.go index f8c22cfcc4..a0db070da5 100644 --- a/services/webdav/pkg/preprocessor/errors.go +++ b/services/webdav/pkg/preprocessor/errors.go @@ -7,4 +7,5 @@ var ( ErrNoConverterForExtractedImageFromGgsFile = errors.New("preprocessor: could not find converter for image extracted from ggs file") ErrNoConverterForExtractedImageFromAudioFile = errors.New("preprocessor: could not find converter for image extracted from audio file") ErrNoConverterForExtractedImageFromGgpFile = errors.New("preprocessor: could not find converter for image extracted from ggp file") + ErrNoThumbnail = errors.New("preprocessor: the document has no thumbnail") ) diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index 7fa944e47c..a264e77ab5 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -6,6 +6,7 @@ import ( "bytes" "encoding/base64" "encoding/json" + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" "image" "image/draw" "image/png" @@ -36,12 +37,13 @@ type Image struct { Data []byte } -// GgsDecoder is a converter for the geogebra slides file +// GgsDecoder is a converter for the geogebra slides file. +// +// Deprecated: Tika provides the thumbnail; kept for setups without Tika. type GgsDecoder struct { thumbnailpath string - // maxSize bounds the extracted image, because a deflated entry expands by - // orders of magnitude and the container's own size says nothing about it. + // a deflated entry expands by orders of magnitude, so its own size says nothing maxSize uint64 } @@ -87,7 +89,9 @@ func (g GgsDecoder) Convert(r io.Reader) (*Image, error) { return nil, errors.Errorf("%s not found", g.thumbnailpath) } -// AudioDecoder is a converter for the audio file +// AudioDecoder is a converter for the audio file. +// +// Deprecated: Tika provides the cover art; kept for setups without Tika. type AudioDecoder struct{} // Convert reads the audio file and extracts the thumbnail image from the id3 tag. @@ -226,7 +230,9 @@ type GGPStruct struct { } } -// GgpDecoder is a converter for the geogebra pinboard file +// GgpDecoder is a converter for the geogebra pinboard file. +// +// Deprecated: see GgsDecoder. type GgpDecoder struct{} // Convert reads the ggp file and returns the first thumbnail image. @@ -355,6 +361,17 @@ type Options struct { FontMapFile string FontFace *opentype.FaceOptions MaxImageSize uint64 + Tika thumbnail.Tika + Filename string +} + +// tikaOr prefers a configured Tika server, else the fallback +func tikaOr(opts Options, mimeType string, fallback FileConverter) FileConverter { + if !opts.Tika.Supports(mimeType) { + return fallback + } + + return TikaThumbnail{tikaURL: opts.Tika.URL, filename: opts.Filename, contentType: opts.Tika.ContentType(mimeType)} } // ForType returns the converter for the specified mimeType @@ -383,18 +400,26 @@ func ForType(mimeType string, opts Options) FileConverter { fontLoader: fontLoader, } case "application/vnd.geogebra.slides": - return GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)} + return tikaOr(opts, mimeType, GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}) case "application/vnd.geogebra.pinboard": - return GgpDecoder{} + return tikaOr(opts, mimeType, GgpDecoder{}) case "audio/flac": fallthrough case "audio/mpeg": fallthrough case "audio/ogg": - return AudioDecoder{} + return tikaOr(opts, mimeType, AudioDecoder{}) default: - // webdav decodes no image: a type without a converter is streamed to - // the generator untouched, which answers whether it can read it. - return nil + // webdav decodes no image: a type without a converter goes to Tika when + // it is configured for it, and is otherwise streamed to the generator + // untouched, which answers whether it can read it. + return tikaOr(opts, mimeType, nil) } } + +// Encoded is an image a converter hands on as it found it. The type decides +// the format the thumbnail is written in. +type Encoded struct { + ContentType string + Data []byte +} diff --git a/services/webdav/pkg/preprocessor/tika.go b/services/webdav/pkg/preprocessor/tika.go new file mode 100644 index 0000000000..781d2fec2c --- /dev/null +++ b/services/webdav/pkg/preprocessor/tika.go @@ -0,0 +1,99 @@ +package preprocessor + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// maxTikaResponse bounds what is read back from Tika +const maxTikaResponse = 100 * 1024 * 1024 + +var tikaHTTPClient = &http.Client{Timeout: 60 * time.Second} + +// TikaThumbnail asks a Tika server for the document's thumbnail. +type TikaThumbnail struct { + tikaURL string + // detection hints + filename string + contentType string +} + +// Convert hands the thumbnail on undecoded: the generator reads formats webdav +// cannot, an .ico icon group out of a PE binary for one. +func (t TikaThumbnail) Convert(r io.Reader) (*Image, error) { + data, err := io.ReadAll(r) + if err != nil { + return nil, err + } + + contentType, img, err := tikaThumbnail(t.tikaURL, t.filename, t.contentType, data) + if err != nil { + return nil, err + } + + return &Image{ContentType: contentType, Data: img}, nil +} + +// tikaThumbnail returns the thumbnail Tika picks (/unpack/thumbnail, Tika >= 4.1) and its content type. +func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, []byte, error) { + if contentType == "" { + contentType = "application/octet-stream" + } + req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/thumbnail?renderThumbnails=true", bytes.NewReader(data)) + if err != nil { + return "", nil, err + } + req.Header.Set("Content-Type", contentType) + req.Header.Set("Accept", "application/json") + if filename != "" { + req.Header.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename)) + } + + resp, err := tikaHTTPClient.Do(req) + if err != nil { + return "", nil, fmt.Errorf("tika request failed: %w", err) + } + defer resp.Body.Close() + + switch resp.StatusCode { + case http.StatusOK: + case http.StatusNoContent: + return "", nil, ErrNoThumbnail + default: + return "", nil, fmt.Errorf("tika thumbnail returned %s", resp.Status) + } + + var body struct { + Metadata map[string]any `json:"metadata"` + Image string `json:"image"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, maxTikaResponse)).Decode(&body); err != nil { + return "", nil, fmt.Errorf("tika thumbnail response: %w", err) + } + img, err := base64.StdEncoding.DecodeString(body.Image) + if err != nil || len(img) == 0 { + return "", nil, fmt.Errorf("tika thumbnail response: no image") + } + return metadataString(body.Metadata, "Content-Type"), img, nil +} + +// metadataString reads a key; values are strings or lists. +func metadataString(meta map[string]any, key string) string { + switch v := meta[key].(type) { + case string: + return v + case []any: + if len(v) > 0 { + if s, ok := v[0].(string); ok { + return s + } + } + } + return "" +} diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go new file mode 100644 index 0000000000..7c0472cb01 --- /dev/null +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -0,0 +1,114 @@ +package preprocessor + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "image" + "image/color" + "image/png" + "net/http" + "net/http/httptest" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" +) + +func pngBytes() []byte { + img := image.NewRGBA(image.Rect(0, 0, 4, 3)) + img.Set(1, 1, color.RGBA{R: 255, A: 255}) + var buf bytes.Buffer + Expect(png.Encode(&buf, img)).To(Succeed()) + return buf.Bytes() +} + +var _ = Describe("TikaThumbnail", func() { + var ( + server *httptest.Server + requests []*http.Request + thumbnail func(w http.ResponseWriter, r *http.Request) + ) + + BeforeEach(func() { + requests = nil + thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r) + if r.URL.Path != "/unpack/thumbnail" { + w.WriteHeader(http.StatusNotFound) + return + } + thumbnail(w, r) + })) + }) + + AfterEach(func() { + server.Close() + }) + + It("takes the thumbnail Tika picks, with its metadata, from one request", func() { + thumbnail = func(w http.ResponseWriter, r *http.Request) { + Expect(r.Method).To(Equal(http.MethodPut)) + Expect(r.URL.Query().Get("renderThumbnails")).To(Equal("true")) + Expect(r.Header.Get("Content-Disposition")).To(ContainSubstring(`filename="shot.nef"`)) + Expect(r.Header.Get("Content-Type")).To(Equal("image/x-nikon-nef"), "the file's type travels as the detection hint") + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "metadata": map[string]any{"Content-Type": "image/png", "tk:embedded-resource-type": "THUMBNAIL"}, + "image": base64.StdEncoding.EncodeToString(pngBytes()), + }) + } + + img, err := TikaThumbnail{tikaURL: server.URL, filename: "shot.nef", contentType: "image/x-nikon-nef"}.Convert(bytes.NewReader([]byte("raw"))) + Expect(err).ToNot(HaveOccurred()) + Expect(img).ToNot(BeNil()) + Expect(requests).To(HaveLen(1)) + }) + + It("reports a document without a thumbnail", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("zip"))) + Expect(err).To(MatchError(ErrNoThumbnail)) + }) + + It("reports a failing server", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) + Expect(err).To(MatchError(ContainSubstring("500"))) + }) + + It("reports a Tika without the endpoint", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) + Expect(err).To(MatchError(ContainSubstring("404"))) + }) +}) + +var _ = Describe("ForType with a Tika server", func() { + It("routes everything Tika is asked for to Tika, text and gif stay native", func() { + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", nil), Filename: "song.mp3"} + Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("application/vnd.geogebra.slides", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("text/plain", opts)).To(BeAssignableToTypeOf(TxtToImageConverter{})) + }) + + It("keeps the in-process converters without a Tika server", func() { + Expect(ForType("audio/mpeg", Options{})).To(BeAssignableToTypeOf(AudioDecoder{})) + Expect(ForType("application/vnd.geogebra.slides", Options{})).To(BeAssignableToTypeOf(GgsDecoder{})) + Expect(ForType("image/x-nikon-nef", Options{})).To(BeNil(), "an image reaches the generator undecoded") + }) + + It("follows a configured list and hands the mapped type to Tika", func() { + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"})} + Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(AudioDecoder{}), "not in the configured list") + Expect(ForType("image/x-nikon-nef", opts).(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon")) + }) +}) diff --git a/services/webdav/pkg/service/v0/service.go b/services/webdav/pkg/service/v0/service.go index 1c4afccb7a..f75457df3b 100644 --- a/services/webdav/pkg/service/v0/service.go +++ b/services/webdav/pkg/service/v0/service.go @@ -216,6 +216,7 @@ func newThumbnailWorkflow(conf *config.Config, sourceTypes thumbnail.SourceTypes workflow.WithMaxInputSize(maxInputSize), workflow.WithSizes(sizes), workflow.WithSourceTypes(sourceTypes), + workflow.WithTika(thumbnail.NewTika(conf.TikaURL, conf.TikaThumbnailMimeTypes)), workflow.WithFormats(formats), workflow.WithTypeMapping(typeMapping), workflow.WithWebdavNamespace(conf.WebdavNamespace), @@ -412,7 +413,6 @@ func (g Webdav) PublicThumbnailHead(w http.ResponseWriter, r *http.Request) { // was attempted, for the log line. func (g Webdav) handleWorkflowError(w http.ResponseWriter, r *http.Request, err error, tr *requests.ThumbnailRequest, logger log.Logger, step string) { var busy *workflow.GeneratorBusyError - logger = log.Logger{Logger: logger.With().Str("step", step).Logger()} switch { @@ -435,6 +435,9 @@ func (g Webdav) handleWorkflowError(w http.ResponseWriter, r *http.Request, err case errors.Is(err, workflow.ErrNotFound): logger.Debug().Err(err).Msg("thumbnail source could not be located") renderError(w, r, errNotFound(notFoundMsg(tr.Filename))) + case errors.Is(err, workflow.ErrNoThumbnail): + logger.Debug().Err(err).Msg("the file carries no thumbnail") + renderError(w, r, errNotFound(notFoundMsg(tr.Filename))) case errors.Is(err, workflow.ErrUnsupportedFileType): logger.Debug().Err(err).Msg("requested for an unsupported file type") renderError(w, r, errNotFound(notFoundMsg(tr.Filename))) diff --git a/services/webdav/pkg/service/v0/thumbnail_errors_test.go b/services/webdav/pkg/service/v0/thumbnail_errors_test.go new file mode 100644 index 0000000000..cc79fa72b5 --- /dev/null +++ b/services/webdav/pkg/service/v0/thumbnail_errors_test.go @@ -0,0 +1,39 @@ +package svc + +import ( + "net/http" + "net/http/httptest" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/services/webdav/pkg/dav/requests" + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail/workflow" +) + +var _ = Describe("thumbnail error mapping", func() { + var ( + g Webdav + tr *requests.ThumbnailRequest + logger log.Logger + ) + + BeforeEach(func() { + logger = log.NopLogger() + g = Webdav{log: logger} + tr = &requests.ThumbnailRequest{Filename: "song.mp3"} + }) + + DescribeTable("a file without a thumbnail is not a server error", + func(step string) { + // clients cache a 404 as "no preview"; a 500 makes them retry forever + rr := httptest.NewRecorder() + g.handleWorkflowError(rr, httptest.NewRequest(http.MethodGet, "/song.mp3", nil), workflow.ErrNoThumbnail, tr, logger, step) + + Expect(rr.Code).To(Equal(http.StatusNotFound)) + }, + Entry("on GET", "thumbnail"), + Entry("on HEAD", "thumbnail head check"), + ) +}) diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go new file mode 100644 index 0000000000..2d7eeed29f --- /dev/null +++ b/services/webdav/pkg/thumbnail/tika.go @@ -0,0 +1,61 @@ +package thumbnail + +import ( + "mime" + "strings" +) + +// Tika is the configured Tika server: its URL and the types it is asked for. +// It only decides which file goes there, the call lives in the preprocessor. +// By default every non-image file is sent and Tika decides. +type Tika struct { + URL string + // our mime type -> Tika's, "" when equal; "*" means every type + mimeTypes map[string]string +} + +// NewTika parses "mime[:tika-mime]" entries; empty means every type. +func NewTika(url string, mimeTypes []string) Tika { + t := Tika{URL: url, mimeTypes: map[string]string{}} + for _, entry := range mimeTypes { + ours, theirs, _ := strings.Cut(strings.ToLower(strings.TrimSpace(entry)), ":") + if ours = strings.TrimSpace(ours); ours != "" { + t.mimeTypes[ours] = strings.TrimSpace(theirs) + } + } + if len(t.mimeTypes) == 0 { + t.mimeTypes["*"] = "" + } + return t +} + +// Supports reports whether the type is sent to Tika for its thumbnail. +func (t Tika) Supports(mimeType string) bool { + if t.URL == "" { + return false + } + m, _, err := mime.ParseMediaType(mimeType) + if err != nil || m == "httpd/unix-directory" { + return false + } + if _, ok := t.mimeTypes[m]; ok { + return true + } + _, all := t.mimeTypes["*"] + return all +} + +// ContentType is the type Tika is told, mapped where configured. Tika takes a +// declared type only when it refines what it detected itself, so a mapping pins +// a subtype its detector left at the parent type, a raw photo it only read as a +// tiff. It cannot overrule a type Tika detected. +func (t Tika) ContentType(mimeType string) string { + m, _, err := mime.ParseMediaType(mimeType) + if err != nil { + return "" + } + if theirs := t.mimeTypes[m]; theirs != "" { + return theirs + } + return m +} diff --git a/services/webdav/pkg/thumbnail/tika_test.go b/services/webdav/pkg/thumbnail/tika_test.go new file mode 100644 index 0000000000..47f4151d84 --- /dev/null +++ b/services/webdav/pkg/thumbnail/tika_test.go @@ -0,0 +1,37 @@ +package thumbnail_test + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" +) + +var _ = Describe("Tika", func() { + none := thumbnail.NewTika("", nil) + all := thumbnail.NewTika("http://tika:9998", nil) + some := thumbnail.NewTika("http://tika:9998", []string{" Application/PDF ", "audio/mpeg", "image/x-nikon-nef:image/x-raw-nikon"}) + + DescribeTable("Supports", + func(tika thumbnail.Tika, mimeType string, want bool) { + Expect(tika.Supports(mimeType)).To(Equal(want)) + }, + Entry("nothing without a server", none, "application/pdf", false), + Entry("everything by default", all, "application/x-anything; charset=binary", true), + Entry("but no directories", all, "httpd/unix-directory", false), + Entry("nor an unparsable type", all, "not a mime", false), + Entry("a listed type", some, "application/pdf", true), + Entry("a listed type with parameters", some, "audio/mpeg; charset=binary", true), + Entry("a mapped type", some, "image/x-nikon-nef", true), + Entry("an unlisted type", some, "application/zip", false), + ) + + DescribeTable("ContentType", + func(tika thumbnail.Tika, mimeType, want string) { + Expect(tika.ContentType(mimeType)).To(Equal(want)) + }, + Entry("maps a type to the one Tika knows", some, "image/x-nikon-nef", "image/x-raw-nikon"), + Entry("passes an unmapped type through, without parameters", some, "application/pdf; charset=binary", "application/pdf"), + Entry("passes everything through by default", all, "audio/mpeg", "audio/mpeg"), + ) +}) diff --git a/services/webdav/pkg/thumbnail/typemapping.go b/services/webdav/pkg/thumbnail/typemapping.go index dc7eefbd1a..fbb5eb796a 100644 --- a/services/webdav/pkg/thumbnail/typemapping.go +++ b/services/webdav/pkg/thumbnail/typemapping.go @@ -11,7 +11,8 @@ import ( // guessed from a file name. Types that carry alpha or animation keep their own // format, everything else becomes a JPEG. An icon is the one type no generator // writes back: it has to become a PNG, or JPEG would flatten its transparent -// pixels onto black. +// pixels onto black. A windows binary is in the list for the same reason, +// although it is no image type itself: what Tika extracts from it is its icon. var DefaultTypeMapping = []string{ "image/png:image/png", "image/gif:image/gif", @@ -23,6 +24,7 @@ var DefaultTypeMapping = []string{ "image/tiff:image/jpeg", "image/vnd.microsoft.icon:image/png", "image/x-icon:image/png", + "application/x-msdownload:image/png", "text/plain:image/jpeg", "audio/flac:image/jpeg", "audio/mpeg:image/jpeg", diff --git a/services/webdav/pkg/thumbnail/typemapping_test.go b/services/webdav/pkg/thumbnail/typemapping_test.go index 4557b75fb1..8b250e18d3 100644 --- a/services/webdav/pkg/thumbnail/typemapping_test.go +++ b/services/webdav/pkg/thumbnail/typemapping_test.go @@ -27,6 +27,10 @@ var _ = Describe("TypeMapping", func() { Expect(m.TargetFor("image/x-icon")).To(Equal("image/png")) }) + It("writes the icon of a windows binary as a png", func() { + Expect(m.TargetFor("application/x-msdownload")).To(Equal("image/png")) + }) + It("reads a type with parameters", func() { Expect(m.TargetFor("image/png; charset=binary")).To(Equal("image/png")) }) diff --git a/services/webdav/pkg/thumbnail/workflow/format_test.go b/services/webdav/pkg/thumbnail/workflow/format_test.go new file mode 100644 index 0000000000..bc7bf6ed4c --- /dev/null +++ b/services/webdav/pkg/thumbnail/workflow/format_test.go @@ -0,0 +1,18 @@ +package workflow + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("thumbnail format", func() { + DescribeTable("typeOfThumbnail reads the type back out of cached bytes", + func(data []byte, contentType string) { + Expect(typeOfThumbnail(data, "fallback")).To(Equal(contentType)) + }, + Entry("png", []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}, "image/png"), + Entry("jpeg", []byte{0xff, 0xd8, 0xff, 0xe0}, "image/jpeg"), + Entry("gif", []byte("GIF89a"), "image/gif"), + Entry("anything else keeps the fallback", []byte("whatever"), "fallback"), + ) +}) diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 0329d8fd44..7ad5f8d181 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -73,6 +73,29 @@ type UserResolver interface { // surface this as HTTP 425 Too Early with a Retry-After header. var ErrFileProcessing = fmt.Errorf("file is processing") +// ErrNoThumbnail is the answer for a file that carries none at all. It is +// cached as an empty entry, so the next request does not ask Tika again. +var ErrNoThumbnail = errors.New("thumbnails: the file has no thumbnail") + +// tikaFormatPlaceholder stands in the cache key for a format only Tika's answer +// reveals, so the entry is found without downloading the file first. +const tikaFormatPlaceholder = "tika" + +// typeOfThumbnail reads the type of bytes that were cached under the +// placeholder, because the key cannot say what they turned out to be. +func typeOfThumbnail(data []byte, fallback string) string { + switch { + case bytes.HasPrefix(data, []byte{0x89, 'P', 'N', 'G'}): + return "image/png" + case bytes.HasPrefix(data, []byte{0xff, 0xd8}): + return "image/jpeg" + case bytes.HasPrefix(data, []byte("GIF8")): + return "image/gif" + } + + return fallback +} + // ErrImageTooLarge is returned when the input image exceeds the configured // maximum width/height. Callers should surface this as HTTP 403 Forbidden. var ErrImageTooLarge = errors.New("thumbnails: image is too large") @@ -148,6 +171,7 @@ type ThumbnailWorkflow struct { sizes *thumbnail.Sizes typeMapping thumbnail.TypeMapping sourceTypes thumbnail.SourceTypes + tika thumbnail.Tika formats generator.Formats webdavNS string fontMapFile string @@ -233,6 +257,11 @@ func WithTypeMapping(m thumbnail.TypeMapping) Option { return func(w *ThumbnailWorkflow) { w.typeMapping = m } } +// WithTika sets the Tika server that thumbnails what webdav cannot read itself. +func WithTika(t thumbnail.Tika) Option { + return func(w *ThumbnailWorkflow) { w.tika = t } +} + // WithFontMapFile sets the font map file used for text thumbnail rendering. func WithFontMapFile(file string) Option { return func(w *ThumbnailWorkflow) { w.fontMapFile = file } @@ -315,7 +344,7 @@ func (w *ThumbnailWorkflow) statSource(ctx context.Context, ref *providerv1beta1 return nil, ErrPermissionDenied } - if !w.sourceTypes.Supports(info.GetMimeType()) { + if !w.supportsMimeType(info.GetMimeType()) { return nil, fmt.Errorf("%w: %s", ErrUnsupportedFileType, info.GetMimeType()) } @@ -423,13 +452,14 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R mimeType := info.GetMimeType() // The thumbnail is returned in the type the source type maps to, asked for by - // the name the generator's filter uses. A type nobody mapped, and one whose - // target the generator cannot write, becomes a JPEG. - outputType, outputFormat := "image/jpeg", "jpg" - if target := w.typeMapping.TargetFor(mimeType); target != "" { - if format := w.formats.For(target); format != "" { - outputType, outputFormat = target, format - } + // the name the generator's filter uses. + outputType, outputFormat := w.outputFor(mimeType) + + // What Tika answers with is only known once it has answered, so the entry is + // keyed under a placeholder until then. + fromTika := !strings.HasPrefix(mimeType, "image/") && w.tika.Supports(mimeType) + if fromTika { + outputFormat = tikaFormatPlaceholder } // The operation is resolved up front so it can be part of the cache key: a @@ -456,6 +486,15 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R cached, err := w.cache.Get(cacheKey) switch { case err == nil: + // an empty entry is a file we know carries no thumbnail + if len(cached) == 0 { + return Thumbnail{}, ErrNoThumbnail + } + if fromTika { + // the format was not known when the entry was written + return Thumbnail{Data: cached, ContentType: typeOfThumbnail(cached, outputType)}, nil + } + return Thumbnail{Data: cached, ContentType: outputType}, nil case !errors.Is(err, cache.ErrCacheMiss): // a miss is the normal answer; anything else is the cache itself @@ -469,18 +508,35 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R // fill/thumbnail/resize the generator may enlarge a small source (e.g. a text // file rendered at a fixed canvas) to fill the snapped box, which is what // imagor's default resize does. - genURL := generator.BuildURL(w.generatorURL, int32(box.Dx()), int32(box.Dy()), operation, outputFormat, noUpscale) - - // Produce the source to send to the generator, never decoding an image in - // webdav: anything without a converter is streamed straight through undecoded, - // the few types with one (text, audio, geogebra) are turned into image bytes here. + // Produce the source image to send to the generator, never decoding an image + // in webdav: real images (incl. gif) are streamed straight through undecoded; + // non-image sources are converted to image bytes here so the generator always + // receives an image. imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, logger) if err != nil { + if errors.Is(err, ErrNoThumbnail) { + // a file that carries no thumbnail is an answer, not a failure, and + // the empty entry keeps the next request from asking again + logger.Debug().Err(err).Msg("no source image for thumbnail") + if w.cache != nil { + _ = w.cache.Put(cacheKey, nil) + } + + return Thumbnail{}, err + } + logger.Error().Err(err).Msg("could not obtain source image for thumbnail") + return Thumbnail{}, err } defer cleanup() + if fromTika { + // only now is the type known that Tika answered with + outputType, outputFormat = w.outputFor(srcType) + } + + genURL := generator.BuildURL(w.generatorURL, int32(box.Dx()), int32(box.Dy()), operation, outputFormat, noUpscale) thumbBytes, thumbType, err := w.postToGenerator(ctx, genURL, imgStream, tr.Filename, srcType) if err != nil { logger.Error().Err(err).Msg("could not generate thumbnail") @@ -515,8 +571,13 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename string, logger log.Logger) (io.Reader, string, func(), error) { m, _, _ := mime.ParseMediaType(mimeType) - converter := preprocessor.ForType(m, preprocessor.Options{FontMapFile: w.fontMapFile, MaxImageSize: w.maxInputSize}) - if converter == nil { + converter := preprocessor.ForType(m, preprocessor.Options{ + FontMapFile: w.fontMapFile, + MaxImageSize: w.maxInputSize, + Tika: w.tika, + Filename: filename, + }) + if strings.HasPrefix(m, "image/") || converter == nil { body, err := w.fileDownloader.DownloadStream(ctx, ref, auth) if err != nil { return nil, "", nil, fmt.Errorf("download: %w", err) @@ -536,6 +597,9 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta } img, err := converter.Convert(bytes.NewReader(fileBytes)) + if errors.Is(err, preprocessor.ErrNoThumbnail) { + return nil, "", nil, ErrNoThumbnail + } if err != nil || img == nil { logger.Debug().Err(err).Msg("could not convert file to image") return nil, "", nil, fmt.Errorf("%w: could not get image", ErrNotFound) @@ -544,6 +608,26 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta return bytes.NewReader(img.Data), img.ContentType, func() {}, nil } +// supportsMimeType reports whether a preview is attempted for the type: the +// announced source types plus whatever a configured Tika takes. +func (w *ThumbnailWorkflow) supportsMimeType(mimeType string) bool { + return w.sourceTypes.Supports(mimeType) || w.tika.Supports(mimeType) +} + +// outputFor is the type a thumbnail of this source is written in and the name +// the generator's format filter has for it. A type nobody mapped, and one whose +// target the generator cannot write, becomes a JPEG. +func (w *ThumbnailWorkflow) outputFor(mimeType string) (outputType, outputFormat string) { + outputType, outputFormat = "image/jpeg", "jpg" + if target := w.typeMapping.TargetFor(mimeType); target != "" { + if format := w.formats.For(target); format != "" { + outputType, outputFormat = target, format + } + } + + return outputType, outputFormat +} + // matchOperation picks how to fit within the box webdav already snapped. A // processor the client named wins, "thumbnail" and "fit" being legacy aliases for // fill and fit-in; without one, an unconstrained axis, then the source type From 48a8e882bd47b2c3f72b1bc14f5b2c9ace1a8cc9 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Sun, 30 Aug 2026 14:04:49 +0200 Subject: [PATCH 02/19] chore(search): read the shared OC_TIKA_URL --- services/search/README.md | 2 +- services/search/pkg/config/content.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/search/README.md b/services/search/README.md index ed2d290f90..86cc93045f 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -155,7 +155,7 @@ As soon as Tika is installed and configured, the search service needs to be told The following settings must be set: * `SEARCH_EXTRACTOR_TYPE=tika` -* `SEARCH_EXTRACTOR_TIKA_TIKA_URL=http://YOUR-TIKA.URL` +* `SEARCH_EXTRACTOR_TIKA_TIKA_URL=http://YOUR-TIKA.URL` (or the shared `OC_TIKA_URL`, which the webdav service reads for thumbnails too) Additionally, the following optional settings can be set: diff --git a/services/search/pkg/config/content.go b/services/search/pkg/config/content.go index d6904f4d87..a4c41bb24f 100644 --- a/services/search/pkg/config/content.go +++ b/services/search/pkg/config/content.go @@ -11,7 +11,7 @@ type Extractor struct { // ExtractorTika configures the Tika extractor type ExtractorTika struct { - TikaURL string `yaml:"tika_url" env:"SEARCH_EXTRACTOR_TIKA_TIKA_URL" desc:"URL of the tika server." introductionVersion:"1.0.0"` + TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;SEARCH_EXTRACTOR_TIKA_TIKA_URL" desc:"URL of the tika server." introductionVersion:"1.0.0"` CleanStopWords bool `yaml:"clean_stop_words" env:"SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS" desc:"Defines if stop words should be cleaned or not. See the documentation for more details." introductionVersion:"1.0.0"` Timeout time.Duration `yaml:"timeout" env:"SEARCH_EXTRACTOR_TIKA_TIMEOUT" desc:"The time one content extraction may take, from downloading the file to the answer of Tika. An extraction that takes longer counts as a failure of the file. 0 disables the limit. See the documentation for more details." introductionVersion:"%%NEXT%%"` } From 69e13657e49107b73225c5c7252aaaca994c83d4 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Sun, 6 Sep 2026 21:46:42 +0200 Subject: [PATCH 03/19] feat(webdav): take the thumbnail tika marks, and the rendering of a metafile --- services/webdav/pkg/preprocessor/tika.go | 143 ++++++++++++++++-- services/webdav/pkg/preprocessor/tika_test.go | 118 +++++++++++++-- 2 files changed, 238 insertions(+), 23 deletions(-) diff --git a/services/webdav/pkg/preprocessor/tika.go b/services/webdav/pkg/preprocessor/tika.go index 781d2fec2c..24b4e9990f 100644 --- a/services/webdav/pkg/preprocessor/tika.go +++ b/services/webdav/pkg/preprocessor/tika.go @@ -1,8 +1,8 @@ package preprocessor import ( + "archive/zip" "bytes" - "encoding/base64" "encoding/json" "fmt" "io" @@ -40,17 +40,20 @@ func (t TikaThumbnail) Convert(r io.Reader) (*Image, error) { return &Image{ContentType: contentType, Data: img}, nil } -// tikaThumbnail returns the thumbnail Tika picks (/unpack/thumbnail, Tika >= 4.1) and its content type. +// tikaThumbnail returns the thumbnail Tika found in the document and its content +// type. Tika 4.1 marks it as a THUMBNAIL embedded document, so /unpack/all is +// enough: no preset, no endpoint of our own. func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, []byte, error) { if contentType == "" { contentType = "application/octet-stream" } - req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/thumbnail?renderThumbnails=true", bytes.NewReader(data)) + req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/all", bytes.NewReader(data)) if err != nil { return "", nil, err } req.Header.Set("Content-Type", contentType) - req.Header.Set("Accept", "application/json") + req.Header.Set("Accept", "application/zip") + // the extension is what routes a raw image to its parser if filename != "" { req.Header.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename)) } @@ -66,21 +69,135 @@ func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, case http.StatusNoContent: return "", nil, ErrNoThumbnail default: - return "", nil, fmt.Errorf("tika thumbnail returned %s", resp.Status) + return "", nil, fmt.Errorf("tika unpack returned %s", resp.Status) } - var body struct { - Metadata map[string]any `json:"metadata"` - Image string `json:"image"` + body, err := io.ReadAll(io.LimitReader(resp.Body, maxTikaResponse)) + if err != nil { + return "", nil, fmt.Errorf("tika unpack response: %w", err) } - if err := json.NewDecoder(io.LimitReader(resp.Body, maxTikaResponse)).Decode(&body); err != nil { - return "", nil, fmt.Errorf("tika thumbnail response: %w", err) + zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) + if err != nil { + return "", nil, fmt.Errorf("tika unpack response: %w", err) } - img, err := base64.StdEncoding.DecodeString(body.Image) + return thumbnailFromUnpack(zr) +} + +// vectorThumbnailTypes are thumbnail types nothing here can decode. Office +// documents carry their preview as a metafile, so the THUMBNAIL entry is a +// vector and the usable image is its rendering. +var vectorThumbnailTypes = map[string]struct{}{ + "image/emf": {}, + "image/wmf": {}, + "image/x-emf": {}, + "image/x-wmf": {}, + "image/svg+xml": {}, +} + +// unpacked is one entry of an /unpack/all response: the bytes and the metadata +// are separate zip entries, "1.jpg" alongside "1.jpg.metadata.json". +type unpacked struct { + name string + kind string + mimeType string + idPath string +} + +// thumbnailFromUnpack picks the image to use out of an unpack response. Tika +// marks the document's preview as THUMBNAIL. For office documents that preview +// is a metafile, and the raster we want is the RENDERING nested under it, which +// tika only emits when its emf/wmf parser has renderImage turned on. +func thumbnailFromUnpack(zr *zip.Reader) (string, []byte, error) { + var entries []unpacked + for _, f := range zr.File { + if !strings.HasSuffix(f.Name, ".metadata.json") { + continue + } + meta, err := readZipJSON(f) + if err != nil { + continue + } + entries = append(entries, unpacked{ + name: strings.TrimSuffix(f.Name, ".metadata.json"), + kind: metadataString(meta, "tk:embedded-resource-type"), + mimeType: metadataString(meta, "Content-Type"), + idPath: metadataString(meta, "tk:embedded-id-path"), + }) + } + + for _, e := range entries { + if e.kind != "THUMBNAIL" { + continue + } + if _, vector := vectorThumbnailTypes[e.mimeType]; !vector { + return readThumbnail(zr, e) + } + if r, ok := renderingOf(entries, e); ok { + return readThumbnail(zr, r) + } + return "", nil, ErrNoThumbnail + } + + // a document without a preview of its own can still have been rendered, + // a pdf page for instance + for _, e := range entries { + if e.kind == "RENDERING" { + return readThumbnail(zr, e) + } + } + return "", nil, ErrNoThumbnail +} + +// renderingOf finds the rendering tika nested under a thumbnail. The rendering +// is a child of the image it renders, so its id path extends the thumbnail's. +func renderingOf(entries []unpacked, thumbnail unpacked) (unpacked, bool) { + for _, e := range entries { + if e.kind == "RENDERING" && thumbnail.idPath != "" && strings.HasPrefix(e.idPath, thumbnail.idPath+"/") { + return e, true + } + } + return unpacked{}, false +} + +func readThumbnail(zr *zip.Reader, e unpacked) (string, []byte, error) { + img, err := readZipEntry(zr, e.name) if err != nil || len(img) == 0 { - return "", nil, fmt.Errorf("tika thumbnail response: no image") + return "", nil, ErrNoThumbnail } - return metadataString(body.Metadata, "Content-Type"), img, nil + return e.mimeType, img, nil +} + +// readZipJSON decodes a metadata entry. Tika writes either an object or a +// single element list. +func readZipJSON(f *zip.File) (map[string]any, error) { + rc, err := f.Open() + if err != nil { + return nil, err + } + defer rc.Close() + + var raw json.RawMessage + if err := json.NewDecoder(io.LimitReader(rc, maxTikaResponse)).Decode(&raw); err != nil { + return nil, err + } + var meta map[string]any + if err := json.Unmarshal(raw, &meta); err == nil { + return meta, nil + } + var list []map[string]any + if err := json.Unmarshal(raw, &list); err != nil || len(list) == 0 { + return nil, fmt.Errorf("unexpected metadata shape") + } + return list[0], nil +} + +func readZipEntry(zr *zip.Reader, name string) ([]byte, error) { + rc, err := zr.Open(name) + if err != nil { + return nil, err + } + defer rc.Close() + return io.ReadAll(io.LimitReader(rc, maxTikaResponse)) } // metadataString reads a key; values are strings or lists. diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index 7c0472cb01..595e10e633 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -1,8 +1,8 @@ package preprocessor import ( + "archive/zip" "bytes" - "encoding/base64" "encoding/json" "image" "image/color" @@ -16,6 +16,25 @@ import ( "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" ) +// unpackZip builds what /unpack/all returns: the entries and their metadata +// side by side, "1.png" next to "1.png.metadata.json". +func unpackZip(entries map[string][]byte, meta map[string]map[string]any) []byte { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for name, data := range entries { + w, err := zw.Create(name) + Expect(err).ToNot(HaveOccurred()) + _, err = w.Write(data) + Expect(err).ToNot(HaveOccurred()) + + w, err = zw.Create(name + ".metadata.json") + Expect(err).ToNot(HaveOccurred()) + Expect(json.NewEncoder(w).Encode(meta[name])).To(Succeed()) + } + Expect(zw.Close()).To(Succeed()) + return buf.Bytes() +} + func pngBytes() []byte { img := image.NewRGBA(image.Rect(0, 0, 4, 3)) img.Set(1, 1, color.RGBA{R: 255, A: 255}) @@ -36,7 +55,7 @@ var _ = Describe("TikaThumbnail", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests = append(requests, r) - if r.URL.Path != "/unpack/thumbnail" { + if r.URL.Path != "/unpack/all" { w.WriteHeader(http.StatusNotFound) return } @@ -48,17 +67,19 @@ var _ = Describe("TikaThumbnail", func() { server.Close() }) - It("takes the thumbnail Tika picks, with its metadata, from one request", func() { + It("takes the entry Tika marked as the thumbnail, in one request", func() { thumbnail = func(w http.ResponseWriter, r *http.Request) { Expect(r.Method).To(Equal(http.MethodPut)) - Expect(r.URL.Query().Get("renderThumbnails")).To(Equal("true")) Expect(r.Header.Get("Content-Disposition")).To(ContainSubstring(`filename="shot.nef"`)) Expect(r.Header.Get("Content-Type")).To(Equal("image/x-nikon-nef"), "the file's type travels as the detection hint") - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "metadata": map[string]any{"Content-Type": "image/png", "tk:embedded-resource-type": "THUMBNAIL"}, - "image": base64.StdEncoding.EncodeToString(pngBytes()), - }) + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"0.nef": []byte("the raw itself"), "1.png": pngBytes()}, + map[string]map[string]any{ + "0.nef": {"Content-Type": "image/x-nikon-nef"}, + "1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "THUMBNAIL"}, + }, + )) } img, err := TikaThumbnail{tikaURL: server.URL, filename: "shot.nef", contentType: "image/x-nikon-nef"}.Convert(bytes.NewReader([]byte("raw"))) @@ -67,6 +88,83 @@ var _ = Describe("TikaThumbnail", func() { Expect(requests).To(HaveLen(1)) }) + It("ignores embedded images that are not the thumbnail", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"1.png": pngBytes()}, + map[string]map[string]any{"1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "INLINE"}}, + )) + } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) + Expect(err).To(MatchError(ErrNoThumbnail), "an inline image is not a thumbnail, tika 4.0 marks cover art that way") + }) + + It("takes the rendering when the thumbnail is a metafile", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"1.wmf": []byte("vector"), "2.png": pngBytes()}, + map[string]map[string]any{ + "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, + "2.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/1/2"}, + }, + )) + } + + img, err := TikaThumbnail{tikaURL: server.URL, filename: "report.doc"}.Convert(bytes.NewReader([]byte("ole2"))) + Expect(err).ToNot(HaveOccurred()) + Expect(img).ToNot(BeNil(), "office documents carry a metafile preview, the raster is its rendering") + }) + + It("reports no thumbnail when the metafile was not rendered", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"1.wmf": []byte("vector")}, + map[string]map[string]any{ + "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, + }, + )) + } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("ole2"))) + Expect(err).To(MatchError(ErrNoThumbnail), "rendering is off in tika by default") + }) + + It("does not take a rendering that belongs to another image", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"1.wmf": []byte("vector"), "3.png": pngBytes()}, + map[string]map[string]any{ + "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, + "3.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/2/3"}, + }, + )) + } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("ole2"))) + Expect(err).To(MatchError(ErrNoThumbnail)) + }) + + It("takes a rendering of the document itself", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(unpackZip( + map[string][]byte{"1.png": pngBytes()}, + map[string]map[string]any{ + "1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/1"}, + }, + )) + } + + img, err := TikaThumbnail{tikaURL: server.URL, filename: "report.pdf"}.Convert(bytes.NewReader([]byte("pdf"))) + Expect(err).ToNot(HaveOccurred()) + Expect(img).ToNot(BeNil(), "a pdf has no preview of its own, a rendered page is one") + }) + It("reports a document without a thumbnail", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } @@ -81,7 +179,7 @@ var _ = Describe("TikaThumbnail", func() { Expect(err).To(MatchError(ContainSubstring("500"))) }) - It("reports a Tika without the endpoint", func() { + It("reports a Tika that does not know the route", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) } _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) From 9dbe0b7956ddd560cec5541f154482940007cc34 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Wed, 16 Sep 2026 13:08:48 +0000 Subject: [PATCH 04/19] feat(webdav): use Tika's merged thumbnail preset Tika merged the thumbnail catalog preset and ThumbnailUnpackSelector (TIKA-4856): PUT /unpack/preset/thumbnail returns exactly the one raster image a client would show for the document, a stored thumbnail, the rendering of a metafile thumbnail, or the rendered first page. The client-side selection over /unpack/all (embedded-resource-type marks, metafile renderings, id-path matching) moves to the server; the preset zip carries one image without metadata sidecars, so the entry's extension names the type and the bytes break the tie. The preset has to be active, so this needs a Tika 4.2.0 or newer started with TIKA_PRESETS=thumbnail, and a 404 says so. --- services/webdav/README.md | 2 +- services/webdav/pkg/config/config.go | 2 +- services/webdav/pkg/preprocessor/tika.go | 149 ++++-------------- services/webdav/pkg/preprocessor/tika_test.go | 120 ++++---------- tests/README.md | 6 +- 5 files changed, 76 insertions(+), 203 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index cc479b900c..6667511865 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,7 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.1 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index 4eee54d7ee..e7c2f3ba45 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -28,7 +28,7 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` - TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.1 or newer with the thumbnail preset active in its configuration." introductionVersion:"%%NEXT%%"` + TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail." introductionVersion:"%%NEXT%%"` TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. Empty means all types that are not handled directly. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` diff --git a/services/webdav/pkg/preprocessor/tika.go b/services/webdav/pkg/preprocessor/tika.go index 24b4e9990f..3c53d20f38 100644 --- a/services/webdav/pkg/preprocessor/tika.go +++ b/services/webdav/pkg/preprocessor/tika.go @@ -3,10 +3,11 @@ package preprocessor import ( "archive/zip" "bytes" - "encoding/json" "fmt" "io" + "mime" "net/http" + "path/filepath" "strings" "time" ) @@ -40,14 +41,18 @@ func (t TikaThumbnail) Convert(r io.Reader) (*Image, error) { return &Image{ContentType: contentType, Data: img}, nil } -// tikaThumbnail returns the thumbnail Tika found in the document and its content -// type. Tika 4.1 marks it as a THUMBNAIL embedded document, so /unpack/all is -// enough: no preset, no endpoint of our own. +// tikaThumbnail returns the thumbnail Tika found in the document and its +// content type. The thumbnail catalog preset (TIKA-4856) unpacks exactly the +// raster image a client would show for the document, a stored thumbnail such as +// a raw photo's embedded preview or an audio file's cover, the rendering of an +// office document's metafile thumbnail, or the rendered first page of a PDF, so +// the zip carries that one image and nothing else. The server has to run with +// TIKA_PRESETS=thumbnail, which needs Tika 4.2.0 or newer. func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, []byte, error) { if contentType == "" { contentType = "application/octet-stream" } - req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/all", bytes.NewReader(data)) + req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/preset/thumbnail", bytes.NewReader(data)) if err != nil { return "", nil, err } @@ -68,6 +73,9 @@ func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, case http.StatusOK: case http.StatusNoContent: return "", nil, ErrNoThumbnail + case http.StatusNotFound: + // the route exists once the catalog preset is active + return "", nil, fmt.Errorf(`tika unpack returned %s: the "thumbnail" preset needs Tika >= 4.2.0 started with TIKA_PRESETS=thumbnail`, resp.Status) default: return "", nil, fmt.Errorf("tika unpack returned %s", resp.Status) } @@ -80,115 +88,41 @@ func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, if err != nil { return "", nil, fmt.Errorf("tika unpack response: %w", err) } - return thumbnailFromUnpack(zr) + return thumbnailFromZip(zr) } -// vectorThumbnailTypes are thumbnail types nothing here can decode. Office -// documents carry their preview as a metafile, so the THUMBNAIL entry is a -// vector and the usable image is its rendering. -var vectorThumbnailTypes = map[string]struct{}{ - "image/emf": {}, - "image/wmf": {}, - "image/x-emf": {}, - "image/x-wmf": {}, - "image/svg+xml": {}, -} - -// unpacked is one entry of an /unpack/all response: the bytes and the metadata -// are separate zip entries, "1.jpg" alongside "1.jpg.metadata.json". -type unpacked struct { - name string - kind string - mimeType string - idPath string -} - -// thumbnailFromUnpack picks the image to use out of an unpack response. Tika -// marks the document's preview as THUMBNAIL. For office documents that preview -// is a metafile, and the raster we want is the RENDERING nested under it, which -// tika only emits when its emf/wmf parser has renderImage turned on. -func thumbnailFromUnpack(zr *zip.Reader) (string, []byte, error) { - var entries []unpacked +// thumbnailFromZip takes the one image the preset unpacked. Lenient about the +// shape: the first regular file that is not a metadata sidecar wins. +// thumbnailFromZip takes the first image in the package Tika answers with. +// What else lies in there is the package's own bookkeeping, and it has been +// renamed before (TIKA-4971 made it datapackage.json and rmeta.json beside an +// unpacked/ directory), so the image is found by what it is, not by where it +// lies or what the others are called. +func thumbnailFromZip(zr *zip.Reader) (string, []byte, error) { for _, f := range zr.File { - if !strings.HasSuffix(f.Name, ".metadata.json") { + if f.FileInfo().IsDir() { continue } - meta, err := readZipJSON(f) - if err != nil { + img, err := readZipEntry(zr, f.Name) + if err != nil || len(img) == 0 { continue } - entries = append(entries, unpacked{ - name: strings.TrimSuffix(f.Name, ".metadata.json"), - kind: metadataString(meta, "tk:embedded-resource-type"), - mimeType: metadataString(meta, "Content-Type"), - idPath: metadataString(meta, "tk:embedded-id-path"), - }) - } - - for _, e := range entries { - if e.kind != "THUMBNAIL" { + contentType := entryContentType(f.Name, img) + if !strings.HasPrefix(contentType, "image/") { continue } - if _, vector := vectorThumbnailTypes[e.mimeType]; !vector { - return readThumbnail(zr, e) - } - if r, ok := renderingOf(entries, e); ok { - return readThumbnail(zr, r) - } - return "", nil, ErrNoThumbnail - } - - // a document without a preview of its own can still have been rendered, - // a pdf page for instance - for _, e := range entries { - if e.kind == "RENDERING" { - return readThumbnail(zr, e) - } + return contentType, img, nil } return "", nil, ErrNoThumbnail } -// renderingOf finds the rendering tika nested under a thumbnail. The rendering -// is a child of the image it renders, so its id path extends the thumbnail's. -func renderingOf(entries []unpacked, thumbnail unpacked) (unpacked, bool) { - for _, e := range entries { - if e.kind == "RENDERING" && thumbnail.idPath != "" && strings.HasPrefix(e.idPath, thumbnail.idPath+"/") { - return e, true - } +// entryContentType names the image's type. The preset zip carries no metadata +// entries, so the extension decides and the bytes break the tie. +func entryContentType(name string, data []byte) string { + if byExt := mime.TypeByExtension(filepath.Ext(name)); byExt != "" { + return byExt } - return unpacked{}, false -} - -func readThumbnail(zr *zip.Reader, e unpacked) (string, []byte, error) { - img, err := readZipEntry(zr, e.name) - if err != nil || len(img) == 0 { - return "", nil, ErrNoThumbnail - } - return e.mimeType, img, nil -} - -// readZipJSON decodes a metadata entry. Tika writes either an object or a -// single element list. -func readZipJSON(f *zip.File) (map[string]any, error) { - rc, err := f.Open() - if err != nil { - return nil, err - } - defer rc.Close() - - var raw json.RawMessage - if err := json.NewDecoder(io.LimitReader(rc, maxTikaResponse)).Decode(&raw); err != nil { - return nil, err - } - var meta map[string]any - if err := json.Unmarshal(raw, &meta); err == nil { - return meta, nil - } - var list []map[string]any - if err := json.Unmarshal(raw, &list); err != nil || len(list) == 0 { - return nil, fmt.Errorf("unexpected metadata shape") - } - return list[0], nil + return http.DetectContentType(data) } func readZipEntry(zr *zip.Reader, name string) ([]byte, error) { @@ -199,18 +133,3 @@ func readZipEntry(zr *zip.Reader, name string) ([]byte, error) { defer rc.Close() return io.ReadAll(io.LimitReader(rc, maxTikaResponse)) } - -// metadataString reads a key; values are strings or lists. -func metadataString(meta map[string]any, key string) string { - switch v := meta[key].(type) { - case string: - return v - case []any: - if len(v) > 0 { - if s, ok := v[0].(string); ok { - return s - } - } - } - return "" -} diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index 595e10e633..3aa0c3dce2 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -3,7 +3,6 @@ package preprocessor import ( "archive/zip" "bytes" - "encoding/json" "image" "image/color" "image/png" @@ -16,9 +15,9 @@ import ( "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" ) -// unpackZip builds what /unpack/all returns: the entries and their metadata -// side by side, "1.png" next to "1.png.metadata.json". -func unpackZip(entries map[string][]byte, meta map[string]map[string]any) []byte { +// presetZip builds what /unpack/preset/thumbnail returns: the image the preset +// selected, and whatever bookkeeping the package carries beside it. +func presetZip(entries map[string][]byte) []byte { var buf bytes.Buffer zw := zip.NewWriter(&buf) for name, data := range entries { @@ -26,10 +25,6 @@ func unpackZip(entries map[string][]byte, meta map[string]map[string]any) []byte Expect(err).ToNot(HaveOccurred()) _, err = w.Write(data) Expect(err).ToNot(HaveOccurred()) - - w, err = zw.Create(name + ".metadata.json") - Expect(err).ToNot(HaveOccurred()) - Expect(json.NewEncoder(w).Encode(meta[name])).To(Succeed()) } Expect(zw.Close()).To(Succeed()) return buf.Bytes() @@ -55,7 +50,7 @@ var _ = Describe("TikaThumbnail", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) } server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests = append(requests, r) - if r.URL.Path != "/unpack/all" { + if r.URL.Path != "/unpack/preset/thumbnail" { w.WriteHeader(http.StatusNotFound) return } @@ -67,19 +62,13 @@ var _ = Describe("TikaThumbnail", func() { server.Close() }) - It("takes the entry Tika marked as the thumbnail, in one request", func() { + It("takes the image the preset unpacked, in one request", func() { thumbnail = func(w http.ResponseWriter, r *http.Request) { Expect(r.Method).To(Equal(http.MethodPut)) Expect(r.Header.Get("Content-Disposition")).To(ContainSubstring(`filename="shot.nef"`)) Expect(r.Header.Get("Content-Type")).To(Equal("image/x-nikon-nef"), "the file's type travels as the detection hint") w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"0.nef": []byte("the raw itself"), "1.png": pngBytes()}, - map[string]map[string]any{ - "0.nef": {"Content-Type": "image/x-nikon-nef"}, - "1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "THUMBNAIL"}, - }, - )) + _, _ = w.Write(presetZip(map[string][]byte{"1.png": pngBytes()})) } img, err := TikaThumbnail{tikaURL: server.URL, filename: "shot.nef", contentType: "image/x-nikon-nef"}.Convert(bytes.NewReader([]byte("raw"))) @@ -88,81 +77,33 @@ var _ = Describe("TikaThumbnail", func() { Expect(requests).To(HaveLen(1)) }) - It("ignores embedded images that are not the thumbnail", func() { - thumbnail = func(w http.ResponseWriter, _ *http.Request) { + It("takes the image out of the package the preset wraps it in", func() { + thumbnail = func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"1.png": pngBytes()}, - map[string]map[string]any{"1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "INLINE"}}, - )) + //the package names its own bookkeeping, and has renamed it before + _, _ = w.Write(presetZip(map[string][]byte{ + "datapackage.json": []byte(`{"resources":[]}`), + "rmeta.json": []byte(`[{"Content-Type":"application/pdf"}]`), + "unpacked/1.png": pngBytes(), + })) } - _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) - Expect(err).To(MatchError(ErrNoThumbnail), "an inline image is not a thumbnail, tika 4.0 marks cover art that way") - }) - - It("takes the rendering when the thumbnail is a metafile", func() { - thumbnail = func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"1.wmf": []byte("vector"), "2.png": pngBytes()}, - map[string]map[string]any{ - "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, - "2.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/1/2"}, - }, - )) - } - - img, err := TikaThumbnail{tikaURL: server.URL, filename: "report.doc"}.Convert(bytes.NewReader([]byte("ole2"))) + img, err := TikaThumbnail{tikaURL: server.URL, filename: "document.pdf"}.Convert(bytes.NewReader([]byte("pdf"))) Expect(err).ToNot(HaveOccurred()) - Expect(img).ToNot(BeNil(), "office documents carry a metafile preview, the raster is its rendering") + Expect(img).ToNot(BeNil()) + Expect(img.ContentType).To(Equal("image/png")) + Expect(img.Data).To(Equal(pngBytes())) }) - It("reports no thumbnail when the metafile was not rendered", func() { + It("decodes an image whose entry name has no telling extension", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"1.wmf": []byte("vector")}, - map[string]map[string]any{ - "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, - }, - )) + _, _ = w.Write(presetZip(map[string][]byte{"thumbnail": pngBytes()})) } - _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("ole2"))) - Expect(err).To(MatchError(ErrNoThumbnail), "rendering is off in tika by default") - }) - - It("does not take a rendering that belongs to another image", func() { - thumbnail = func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"1.wmf": []byte("vector"), "3.png": pngBytes()}, - map[string]map[string]any{ - "1.wmf": {"Content-Type": "image/wmf", "tk:embedded-resource-type": "THUMBNAIL", "tk:embedded-id-path": "/1"}, - "3.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/2/3"}, - }, - )) - } - - _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("ole2"))) - Expect(err).To(MatchError(ErrNoThumbnail)) - }) - - It("takes a rendering of the document itself", func() { - thumbnail = func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(unpackZip( - map[string][]byte{"1.png": pngBytes()}, - map[string]map[string]any{ - "1.png": {"Content-Type": "image/png", "tk:embedded-resource-type": "RENDERING", "tk:embedded-id-path": "/1"}, - }, - )) - } - - img, err := TikaThumbnail{tikaURL: server.URL, filename: "report.pdf"}.Convert(bytes.NewReader([]byte("pdf"))) + img, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) Expect(err).ToNot(HaveOccurred()) - Expect(img).ToNot(BeNil(), "a pdf has no preview of its own, a rendered page is one") + Expect(img).ToNot(BeNil(), "the bytes name the type when the entry does not") }) It("reports a document without a thumbnail", func() { @@ -172,6 +113,16 @@ var _ = Describe("TikaThumbnail", func() { Expect(err).To(MatchError(ErrNoThumbnail)) }) + It("reports an empty zip as no thumbnail", func() { + thumbnail = func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(presetZip(nil)) + } + + _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("zip"))) + Expect(err).To(MatchError(ErrNoThumbnail)) + }) + It("reports a failing server", func() { thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) } @@ -179,11 +130,10 @@ var _ = Describe("TikaThumbnail", func() { Expect(err).To(MatchError(ContainSubstring("500"))) }) - It("reports a Tika that does not know the route", func() { - thumbnail = func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) } - - _, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw"))) + It("points at the preset activation when the route is missing", func() { + _, err := TikaThumbnail{tikaURL: server.URL + "/nowhere"}.Convert(bytes.NewReader([]byte("raw"))) Expect(err).To(MatchError(ContainSubstring("404"))) + Expect(err).To(MatchError(ContainSubstring("preset")), "a 404 means the catalog preset is not active") }) }) diff --git a/tests/README.md b/tests/README.md index b40a85be56..1511e004f9 100644 --- a/tests/README.md +++ b/tests/README.md @@ -367,9 +367,13 @@ Test suites that are tagged with `@tikaServiceNeeded` require tika service. Run the following docker command to setup tika service ```bash -docker run -d -p 127.0.0.1:9998:9998 apache/tika +docker run -d -p 127.0.0.1:9998:9998 -e TIKA_PRESETS=thumbnail apache/tika:4.2.0-SNAPSHOT-full ``` +The thumbnail suites ask Tika for `PUT /unpack/preset/thumbnail`, which the +`thumbnail` catalog preset serves, so it has to be activated and Tika has to be +4.2.0 or newer. The `-full` image carries the parsers the preset reads. + #### Run OpenCloud TODO: Documentation related to the content based search and tika extractor will be added later. From 299586bf7daf72b1c70e1a37b661133169367b52 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Wed, 7 Oct 2026 20:39:18 +0200 Subject: [PATCH 05/19] ci: activate Tika's thumbnail preset wherever Tika runs PUT /unpack/preset/thumbnail answers 404 unless the thumbnail catalog preset is active, and the thumbnailer then finds no thumbnail for any document. TIKA_PRESETS=thumbnail activates it and needs Tika 4.2.0, so the acceptance stack and the example deployment follow the snapshot image until the release is out. The deployment also reads the shared OC_TIKA_URL so the thumbnailer uses the Tika that is already there. --- .woodpecker.star | 4 ++++ devtools/deployments/opencloud_full/tika.yml | 7 +++++-- tests/acceptance/docker/src/tika.yml | 4 +++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.woodpecker.star b/.woodpecker.star index 68cbb10ff9..f46fbfc0a0 100644 --- a/.woodpecker.star +++ b/.woodpecker.star @@ -3385,6 +3385,10 @@ def tikaService(): # tika 4 discovers its plugins relative to the image working directory, # the workspace default would leave the pipes fetchers empty "directory": "/opt/tika-server", + "environment": { + # the thumbnail preset ships inert, this activates it + "TIKA_PRESETS": "thumbnail", + }, "detach": True, }, { "name": "wait-for-tika-service", diff --git a/devtools/deployments/opencloud_full/tika.yml b/devtools/deployments/opencloud_full/tika.yml index 081f2876b5..ca796a02b6 100644 --- a/devtools/deployments/opencloud_full/tika.yml +++ b/devtools/deployments/opencloud_full/tika.yml @@ -1,8 +1,11 @@ --- services: tika: - image: ${TIKA_IMAGE:-apache/tika:latest-full} + image: ${TIKA_IMAGE:-apache/tika:4.2.0-SNAPSHOT-full} # release notes: https://tika.apache.org + environment: + # the thumbnail preset ships inert, this activates it, Tika 4.2.0 or newer + TIKA_PRESETS: thumbnail networks: opencloud-net: restart: always @@ -13,5 +16,5 @@ services: environment: # fulltext search SEARCH_EXTRACTOR_TYPE: tika - SEARCH_EXTRACTOR_TIKA_TIKA_URL: http://tika:9998 + OC_TIKA_URL: http://tika:9998 FRONTEND_FULL_TEXT_SEARCH_ENABLED: "true" diff --git a/tests/acceptance/docker/src/tika.yml b/tests/acceptance/docker/src/tika.yml index 36bc0a905e..f46d0f6e13 100644 --- a/tests/acceptance/docker/src/tika.yml +++ b/tests/acceptance/docker/src/tika.yml @@ -5,4 +5,6 @@ services: - tika command: tika:9998 tika: - image: apache/tika:4.1.0-full + image: apache/tika:4.2.0-SNAPSHOT-full + environment: + TIKA_PRESETS: thumbnail From 6b2c30219c0592802532a6ccc2748902ccf71a89 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Mon, 19 Oct 2026 11:54:28 +0200 Subject: [PATCH 06/19] refactor(webdav): let the preprocessor say what a type needs The cache key is derived from configuration again: a thumbnail is written in the type the file's own type maps to, so the answer no longer depends on what Tika hands back and needs no placeholder in the key. Which types Tika gets is decided in one place now. An image type goes to Tika only when a deployment names it, because the generator behind the URL may read it itself, which also lets a raw photo reach Tika at all. --- services/webdav/README.md | 2 +- .../webdav/pkg/preprocessor/preprocessor.go | 18 +++-- services/webdav/pkg/preprocessor/tika_test.go | 5 +- services/webdav/pkg/thumbnail/sourcetypes.go | 16 +++-- services/webdav/pkg/thumbnail/tika.go | 17 +++++ .../pkg/thumbnail/workflow/format_test.go | 18 ----- .../webdav/pkg/thumbnail/workflow/workflow.go | 69 +++++-------------- 7 files changed, 58 insertions(+), 87 deletions(-) delete mode 100644 services/webdav/pkg/thumbnail/workflow/format_test.go diff --git a/services/webdav/README.md b/services/webdav/README.md index 6667511865..b7f72ca064 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,7 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index a264e77ab5..41953c9264 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -410,16 +410,14 @@ func ForType(mimeType string, opts Options) FileConverter { case "audio/ogg": return tikaOr(opts, mimeType, AudioDecoder{}) default: - // webdav decodes no image: a type without a converter goes to Tika when - // it is configured for it, and is otherwise streamed to the generator - // untouched, which answers whether it can read it. + // an image reaches the generator as it is: it reads the common types and + // may read more, an imagor with ImageMagick reads heic where we do not. + // OC_TIKA_THUMBNAIL_MIME_TYPES is how a deployment hands an image type + // to Tika instead. + if strings.HasPrefix(mimeType, "image/") && !opts.Tika.ConfiguredFor(mimeType) { + return nil + } + return tikaOr(opts, mimeType, nil) } } - -// Encoded is an image a converter hands on as it found it. The type decides -// the format the thumbnail is written in. -type Encoded struct { - ContentType string - Data []byte -} diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index 3aa0c3dce2..c86822c556 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -141,10 +141,11 @@ var _ = Describe("ForType with a Tika server", func() { It("routes everything Tika is asked for to Tika, text and gif stay native", func() { opts := Options{Tika: thumbnail.NewTika("http://tika:9998", nil), Filename: "song.mp3"} Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/vnd.geogebra.slides", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("text/plain", opts)).To(BeAssignableToTypeOf(TxtToImageConverter{})) + Expect(ForType("image/png", opts)).To(BeNil(), "the generator reads a png itself") + Expect(ForType("image/x-nikon-nef", opts)).To(BeNil(), "an image type the catch-all does not take, the generator may read it") }) It("keeps the in-process converters without a Tika server", func() { @@ -157,6 +158,6 @@ var _ = Describe("ForType with a Tika server", func() { opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"})} Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(AudioDecoder{}), "not in the configured list") - Expect(ForType("image/x-nikon-nef", opts).(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon")) + Expect(ForType("image/x-nikon-nef", opts).(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon"), "a named image type does go to Tika") }) }) diff --git a/services/webdav/pkg/thumbnail/sourcetypes.go b/services/webdav/pkg/thumbnail/sourcetypes.go index 7a085e00b7..63d1ba0128 100644 --- a/services/webdav/pkg/thumbnail/sourcetypes.go +++ b/services/webdav/pkg/thumbnail/sourcetypes.go @@ -6,11 +6,10 @@ import ( "strings" ) -// DefaultSourceTypes are the types a preview is announced and attempted for -// without further configuration. The image types are what both resize backends -// read; the others are converted to an image here, by a preprocessor, before a -// generator ever sees them. -var DefaultSourceTypes = []string{ +// GeneratorImageTypes are the image types both resize backends read, so webdav +// hands the file to the generator as it is. Every other type needs something to +// make an image of it first, a preprocessor here or a Tika server. +var GeneratorImageTypes = []string{ "image/png", "image/jpg", "image/jpeg", @@ -19,13 +18,18 @@ var DefaultSourceTypes = []string{ "image/x-ms-bmp", "image/tiff", "image/webp", +} + +// DefaultSourceTypes are the types a preview is announced and attempted for +// without further configuration. +var DefaultSourceTypes = slices.Concat(GeneratorImageTypes, []string{ "text/plain", "audio/flac", "audio/mpeg", "audio/ogg", "application/vnd.geogebra.slides", "application/vnd.geogebra.pinboard", -} +}) // SourceTypes are the types a preview is announced and attempted for: the // defaults plus what a deployment configured, which is also the list the diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index 2d7eeed29f..68a3ccd94e 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -45,6 +45,23 @@ func (t Tika) Supports(mimeType string) bool { return all } +// ConfiguredFor reports whether OC_TIKA_THUMBNAIL_MIME_TYPES lists this type, +// as opposed to the catch-all taking it. An image is only taken away from the +// generator when the configuration asks for it, because the generator may well +// read the type itself. +func (t Tika) ConfiguredFor(mimeType string) bool { + if t.URL == "" { + return false + } + m, _, err := mime.ParseMediaType(mimeType) + if err != nil { + return false + } + _, named := t.mimeTypes[m] + + return named +} + // ContentType is the type Tika is told, mapped where configured. Tika takes a // declared type only when it refines what it detected itself, so a mapping pins // a subtype its detector left at the parent type, a raw photo it only read as a diff --git a/services/webdav/pkg/thumbnail/workflow/format_test.go b/services/webdav/pkg/thumbnail/workflow/format_test.go deleted file mode 100644 index bc7bf6ed4c..0000000000 --- a/services/webdav/pkg/thumbnail/workflow/format_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package workflow - -import ( - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("thumbnail format", func() { - DescribeTable("typeOfThumbnail reads the type back out of cached bytes", - func(data []byte, contentType string) { - Expect(typeOfThumbnail(data, "fallback")).To(Equal(contentType)) - }, - Entry("png", []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}, "image/png"), - Entry("jpeg", []byte{0xff, 0xd8, 0xff, 0xe0}, "image/jpeg"), - Entry("gif", []byte("GIF89a"), "image/gif"), - Entry("anything else keeps the fallback", []byte("whatever"), "fallback"), - ) -}) diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 7ad5f8d181..2c3190a1ac 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -77,25 +77,6 @@ var ErrFileProcessing = fmt.Errorf("file is processing") // cached as an empty entry, so the next request does not ask Tika again. var ErrNoThumbnail = errors.New("thumbnails: the file has no thumbnail") -// tikaFormatPlaceholder stands in the cache key for a format only Tika's answer -// reveals, so the entry is found without downloading the file first. -const tikaFormatPlaceholder = "tika" - -// typeOfThumbnail reads the type of bytes that were cached under the -// placeholder, because the key cannot say what they turned out to be. -func typeOfThumbnail(data []byte, fallback string) string { - switch { - case bytes.HasPrefix(data, []byte{0x89, 'P', 'N', 'G'}): - return "image/png" - case bytes.HasPrefix(data, []byte{0xff, 0xd8}): - return "image/jpeg" - case bytes.HasPrefix(data, []byte("GIF8")): - return "image/gif" - } - - return fallback -} - // ErrImageTooLarge is returned when the input image exceeds the configured // maximum width/height. Callers should surface this as HTTP 403 Forbidden. var ErrImageTooLarge = errors.New("thumbnails: image is too large") @@ -451,17 +432,14 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R } mimeType := info.GetMimeType() - // The thumbnail is returned in the type the source type maps to, asked for by - // the name the generator's filter uses. + // The thumbnail is returned in the type the source type maps to, asked for + // by the name the generator's filter uses. What an extractor hands on is + // re-encoded to that type, because the request has to decide it: a cache + // hit knows the key, not the bytes. Keeping a png cover a png needs the + // embedded type before the key is built, which is what the preview presence + // work puts into the file's metadata. outputType, outputFormat := w.outputFor(mimeType) - // What Tika answers with is only known once it has answered, so the entry is - // keyed under a placeholder until then. - fromTika := !strings.HasPrefix(mimeType, "image/") && w.tika.Supports(mimeType) - if fromTika { - outputFormat = tikaFormatPlaceholder - } - // The operation is resolved up front so it can be part of the cache key: a // fill and a fit-in request with the same dimensions produce different images // and must not share a cache entry. noUpscale reports whether the generator @@ -490,10 +468,6 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R if len(cached) == 0 { return Thumbnail{}, ErrNoThumbnail } - if fromTika { - // the format was not known when the entry was written - return Thumbnail{Data: cached, ContentType: typeOfThumbnail(cached, outputType)}, nil - } return Thumbnail{Data: cached, ContentType: outputType}, nil case !errors.Is(err, cache.ErrCacheMiss): @@ -503,11 +477,6 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R } } - // webdav snaps the requested size onto a configured resolution and lets the - // generator fill that box. Only fit-in suppresses upscaling (noUpscale); for - // fill/thumbnail/resize the generator may enlarge a small source (e.g. a text - // file rendered at a fixed canvas) to fill the snapped box, which is what - // imagor's default resize does. // Produce the source image to send to the generator, never decoding an image // in webdav: real images (incl. gif) are streamed straight through undecoded; // non-image sources are converted to image bytes here so the generator always @@ -531,11 +500,11 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R } defer cleanup() - if fromTika { - // only now is the type known that Tika answered with - outputType, outputFormat = w.outputFor(srcType) - } - + // webdav snaps the requested size onto a configured resolution and lets the + // generator fill that box. Only fit-in suppresses upscaling (noUpscale); for + // fill/thumbnail/resize the generator may enlarge a small source (e.g. a text + // file rendered at a fixed canvas) to fill the snapped box, which is what + // imagor's default resize does. genURL := generator.BuildURL(w.generatorURL, int32(box.Dx()), int32(box.Dy()), operation, outputFormat, noUpscale) thumbBytes, thumbType, err := w.postToGenerator(ctx, genURL, imgStream, tr.Filename, srcType) if err != nil { @@ -571,24 +540,24 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename string, logger log.Logger) (io.Reader, string, func(), error) { m, _, _ := mime.ParseMediaType(mimeType) - converter := preprocessor.ForType(m, preprocessor.Options{ + // the preprocessor decides what a type needs. No converter means the file + // is handed to the generator as it is, which is the case for every type it + // reads itself. + converter := preprocessor.ForType(mimeType, preprocessor.Options{ FontMapFile: w.fontMapFile, MaxImageSize: w.maxInputSize, Tika: w.tika, Filename: filename, }) - if strings.HasPrefix(m, "image/") || converter == nil { - body, err := w.fileDownloader.DownloadStream(ctx, ref, auth) - if err != nil { - return nil, "", nil, fmt.Errorf("download: %w", err) - } - return body, m, func() { _ = body.Close() }, nil - } body, err := w.fileDownloader.DownloadStream(ctx, ref, auth) if err != nil { return nil, "", nil, fmt.Errorf("download: %w", err) } + + if converter == nil { + return body, m, func() { _ = body.Close() }, nil + } defer body.Close() fileBytes, err := io.ReadAll(body) From 5d98850cd9e4dae71f119cd16c5816fb85eb4d3b Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Tue, 20 Oct 2026 02:29:28 +0200 Subject: [PATCH 07/19] feat(webdav): extract a source image once per file, not once per size What an extractor makes of a file does not depend on the size that was asked for, so it is kept under one key per file and read before the file is even downloaded. An empty entry says the file carries nothing, which keeps the next size from asking Tika again; a failed extraction is not remembered. The file cache now replaces what a key holds, as the other two backends already did, because an entry whose value can change has to be replaceable. --- services/webdav/README.md | 2 +- .../webdav/pkg/thumbnail/cache/cache_test.go | 21 ++----- .../webdav/pkg/thumbnail/cache/filecache.go | 4 -- .../webdav/pkg/thumbnail/workflow/workflow.go | 54 ++++++++++++++++- .../pkg/thumbnail/workflow/workflow_test.go | 59 +++++++++++++++++++ 5 files changed, 116 insertions(+), 24 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index b7f72ca064..32364c13f7 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -12,7 +12,7 @@ The webdav service provides various `GET` endpoints to get the thumbnails of a f When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. -Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. +Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. #### Thumbnail Query String Parameters diff --git a/services/webdav/pkg/thumbnail/cache/cache_test.go b/services/webdav/pkg/thumbnail/cache/cache_test.go index 2836ff0d1d..305015fc99 100644 --- a/services/webdav/pkg/thumbnail/cache/cache_test.go +++ b/services/webdav/pkg/thumbnail/cache/cache_test.go @@ -456,27 +456,14 @@ var _ = Describe("FileCache", func() { Expect(original).To(Equal([]byte("original"))) }) - It("should be idempotent - Put is no-op if file already exists", func() { + It("should overwrite existing keys", func() { key := "ab/cd/ef1234567890/400x400.jpg" - err := cache.Put(key, []byte("v1")) - Expect(err).ToNot(HaveOccurred()) - - info1, err := os.Stat(filepath.Join(tmpdir, "ab", "cd", "ef1234567890", "400x400.jpg")) - Expect(err).ToNot(HaveOccurred()) - modTime1 := info1.ModTime() - - time.Sleep(10 * time.Millisecond) - - err = cache.Put(key, []byte("v2")) - Expect(err).ToNot(HaveOccurred()) + Expect(cache.Put(key, []byte("v1"))).To(Succeed()) + Expect(cache.Put(key, []byte("v2"))).To(Succeed()) data, err := cache.Get(key) Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal([]byte("v1"))) - - info2, err := os.Stat(filepath.Join(tmpdir, "ab", "cd", "ef1234567890", "400x400.jpg")) - Expect(err).ToNot(HaveOccurred()) - Expect(info2.ModTime()).To(Equal(modTime1)) + Expect(data).To(Equal([]byte("v2")), "a key whose value can change has to be replaceable") }) It("should handle empty data", func() { diff --git a/services/webdav/pkg/thumbnail/cache/filecache.go b/services/webdav/pkg/thumbnail/cache/filecache.go index 046c14cd5e..984e8d364e 100644 --- a/services/webdav/pkg/thumbnail/cache/filecache.go +++ b/services/webdav/pkg/thumbnail/cache/filecache.go @@ -36,10 +36,6 @@ func (c *FileCache) Put(key string, data []byte) error { imgPath := filepath.Join(c.dir, key) dir := filepath.Dir(imgPath) - if _, err := os.Stat(imgPath); err == nil { - return nil - } - if err := os.MkdirAll(dir, 0700); err != nil { return err } diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 2c3190a1ac..5a9c7ba5fc 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -142,6 +142,17 @@ func thumbnailStorageKey(checksum, mimeType string, w, h int, format, operation return hash[:2] + "/" + hash[2:4] + "/" + hash[4:] + "/" + fmt.Sprintf("%dx%d-%s.%s", w, h, operation, format) } +// sourceStorageKey is where the image an extractor made of a file is +// remembered. What an extractor finds does not depend on the size that was +// asked for, so this one entry answers every request for the file, and an +// empty entry says the file carries no image at all. +func sourceStorageKey(checksum string) string { + if len(checksum) >= 6 { + return checksum[:2] + "/" + checksum[2:4] + "/" + checksum[4:] + "/source" + } + return checksum + "/source" +} + // ThumbnailWorkflow owns the complete thumbnail generation pipeline: // stat → validate → cache check → download → preprocess → generate → cache → respond. type ThumbnailWorkflow struct { @@ -481,7 +492,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R // in webdav: real images (incl. gif) are streamed straight through undecoded; // non-image sources are converted to image bytes here so the generator always // receives an image. - imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, logger) + imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, checksum, logger) if err != nil { if errors.Is(err, ErrNoThumbnail) { // a file that carries no thumbnail is an answer, not a failure, and @@ -537,7 +548,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R // generator decides whether it can read it. // - text/plain is rendered to an image here (the only true conversion). // - audio and geogebra sources have their embedded image extracted to bytes. -func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename string, logger log.Logger) (io.Reader, string, func(), error) { +func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename, checksum string, logger log.Logger) (io.Reader, string, func(), error) { m, _, _ := mime.ParseMediaType(mimeType) // the preprocessor decides what a type needs. No converter means the file @@ -550,6 +561,22 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta Filename: filename, }) + // what the extraction found is remembered per file, so a second size does + // not send the file to Tika again, and a file that carries nothing is only + // asked once. The answer is read before the file is downloaded at all. + sourceKey := sourceStorageKey(checksum) + if converter != nil && w.cache != nil { + if cached, err := w.cache.Get(sourceKey); err == nil { + if len(cached) == 0 { + return nil, "", nil, ErrNoThumbnail + } + + //the cache holds bytes, so the type comes from them: the generator + //sniffs them too, this only tells it what to expect + return bytes.NewReader(cached), http.DetectContentType(cached), func() {}, nil + } + } + body, err := w.fileDownloader.DownloadStream(ctx, ref, auth) if err != nil { return nil, "", nil, fmt.Errorf("download: %w", err) @@ -567,16 +594,39 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta img, err := converter.Convert(bytes.NewReader(fileBytes)) if errors.Is(err, preprocessor.ErrNoThumbnail) { + //the file carries no image, which is an answer and worth remembering; + //a failed extraction is not, it may succeed on the next try + w.rememberSource(sourceKey, nil) return nil, "", nil, ErrNoThumbnail } if err != nil || img == nil { logger.Debug().Err(err).Msg("could not convert file to image") return nil, "", nil, fmt.Errorf("%w: could not get image", ErrNotFound) } + w.rememberSource(sourceKey, img.Data) return bytes.NewReader(img.Data), img.ContentType, func() {}, nil } +// maxCachedSourceBytes bounds one remembered source image. A preview a camera +// embeds is about a megabyte, a rendered page a few; the limit is what keeps +// the memory backend, which evicts in insertion order, from throwing out the +// thumbnails it serves to make room for one source. +const maxCachedSourceBytes = 8 << 20 + +// rememberSource keeps what an extractor made of a file, or the empty entry +// that says it made nothing. An image too large to keep is simply not kept: +// the extraction runs again next time, which costs time, not correctness. +func (w *ThumbnailWorkflow) rememberSource(key string, data []byte) { + if w.cache == nil || len(data) > maxCachedSourceBytes { + return + } + if w.maxInputSize > 0 && uint64(len(data)) > w.maxInputSize { + return + } + _ = w.cache.Put(key, data) +} + // supportsMimeType reports whether a preview is attempted for the type: the // announced source types plus whatever a configured Tika takes. func (w *ThumbnailWorkflow) supportsMimeType(mimeType string) bool { diff --git a/services/webdav/pkg/thumbnail/workflow/workflow_test.go b/services/webdav/pkg/thumbnail/workflow/workflow_test.go index ad94b110e0..94d2a72aea 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow_test.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow_test.go @@ -829,6 +829,65 @@ var _ = Describe("ThumbnailWorkflow", func() { Expect(captured.data).ToNot(Equal(mp3Bytes)) }) + It("keeps what an extractor found, under one key for the whole file", func() { + mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3")) + Expect(err).ToNot(HaveOccurred()) + + wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes) + + tr := &requests.ThumbnailRequest{ + Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"), + Filename: "song.mp3", + Width: 64, + Height: 64, + } + + _, err = wf2.Execute(context.Background(), tr, testToken, logger) + Expect(err).ToNot(HaveOccurred()) + + cached, err := testCache.Get("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source") + Expect(err).ToNot(HaveOccurred()) + Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size") + }) + + It("sends the kept source instead of extracting a second time", func() { + pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png")) + Expect(err).ToNot(HaveOccurred()) + Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", pngBytes)).To(Succeed()) + + //the file itself is not an mp3: extracting it would fail, so what + //reaches the generator can only come from the cache + wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3")) + + tr := &requests.ThumbnailRequest{ + Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"), + Filename: "song.mp3", + Width: 128, + Height: 128, + } + + _, err = wf2.Execute(context.Background(), tr, testToken, logger) + Expect(err).ToNot(HaveOccurred()) + Expect(captured.data).To(Equal(pngBytes)) + }) + + It("asks once for a file that carries nothing, whatever size follows", func() { + Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", nil)).To(Succeed()) + + wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3")) + + tr := &requests.ThumbnailRequest{ + Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"), + Filename: "song.mp3", + Width: 256, + Height: 256, + } + + _, err := wf2.Execute(context.Background(), tr, testToken, logger) + Expect(err).To(MatchError(ErrNoThumbnail)) + Expect(captured.data).To(BeEmpty(), "the generator is not asked at all") + }) + It("extracts the embedded thumbnail from geogebra slides", func() { ggsBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "ggs_test.ggs")) Expect(err).ToNot(HaveOccurred()) From 31b6cf6bd9127d19f6b387c5c706a808807bbd9b Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 23 Oct 2026 10:27:19 +0200 Subject: [PATCH 08/19] docs(webdav): say how a Tika before 4.2.0 activates the preset Both answer with the same image for the same file, only the package differs, and a 4.1.x server has no preview for erf, orf and rw2. The 404 now names both ways to activate the preset. --- services/webdav/README.md | 15 +++++++++++++++ services/webdav/pkg/config/config.go | 2 +- services/webdav/pkg/preprocessor/tika.go | 14 ++++++-------- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index 32364c13f7..ff2c9ddee2 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -14,6 +14,21 @@ When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 o Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. +#### Tika Before 4.2.0 + +`TIKA_PRESETS` is read by Tika 4.2.0 and newer. A 4.1.x server serves the same +route when its config file activates the preset: + +```json +{ + "server": { "port": 9998, "host": "0.0.0.0" }, + "presets": { "thumbnail": true } +} +``` + +It is passed with `-c /tika-config.json`, and the `server` block has to be in +there because the file replaces what the command line would say. + #### Thumbnail Query String Parameters Clients can request thumbnail previews for files by adding `?preview=1` to the file URL. Requests for files with no thumbnail available respond with HTTP status `404`. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index e7c2f3ba45..f4a8d261fc 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -28,7 +28,7 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` - TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail." introductionVersion:"%%NEXT%%"` + TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. Empty means all types that are not handled directly. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` diff --git a/services/webdav/pkg/preprocessor/tika.go b/services/webdav/pkg/preprocessor/tika.go index 3c53d20f38..56b2b813d2 100644 --- a/services/webdav/pkg/preprocessor/tika.go +++ b/services/webdav/pkg/preprocessor/tika.go @@ -45,9 +45,9 @@ func (t TikaThumbnail) Convert(r io.Reader) (*Image, error) { // content type. The thumbnail catalog preset (TIKA-4856) unpacks exactly the // raster image a client would show for the document, a stored thumbnail such as // a raw photo's embedded preview or an audio file's cover, the rendering of an -// office document's metafile thumbnail, or the rendered first page of a PDF, so -// the zip carries that one image and nothing else. The server has to run with -// TIKA_PRESETS=thumbnail, which needs Tika 4.2.0 or newer. +// office document's metafile thumbnail, or the rendered first page of a PDF. +// The server has to run with the preset active: Tika 4.2.0 or newer takes +// TIKA_PRESETS=thumbnail, a 4.1.x server activates it in its config file. func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, []byte, error) { if contentType == "" { contentType = "application/octet-stream" @@ -75,7 +75,7 @@ func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, return "", nil, ErrNoThumbnail case http.StatusNotFound: // the route exists once the catalog preset is active - return "", nil, fmt.Errorf(`tika unpack returned %s: the "thumbnail" preset needs Tika >= 4.2.0 started with TIKA_PRESETS=thumbnail`, resp.Status) + return "", nil, fmt.Errorf(`tika unpack returned %s: the "thumbnail" preset is not active, start Tika 4.2.0 or newer with TIKA_PRESETS=thumbnail, or a 4.1.x server with "presets": {"thumbnail": true} in its config`, resp.Status) default: return "", nil, fmt.Errorf("tika unpack returned %s", resp.Status) } @@ -91,8 +91,6 @@ func tikaThumbnail(tikaURL, filename, contentType string, data []byte) (string, return thumbnailFromZip(zr) } -// thumbnailFromZip takes the one image the preset unpacked. Lenient about the -// shape: the first regular file that is not a metadata sidecar wins. // thumbnailFromZip takes the first image in the package Tika answers with. // What else lies in there is the package's own bookkeeping, and it has been // renamed before (TIKA-4971 made it datapackage.json and rmeta.json beside an @@ -116,8 +114,8 @@ func thumbnailFromZip(zr *zip.Reader) (string, []byte, error) { return "", nil, ErrNoThumbnail } -// entryContentType names the image's type. The preset zip carries no metadata -// entries, so the extension decides and the bytes break the tie. +// entryContentType names the image's type: the extension decides and the bytes +// break the tie. func entryContentType(name string, data []byte) string { if byExt := mime.TypeByExtension(filepath.Ext(name)); byExt != "" { return byExt From f24659fdf48d429f218a4c7bb76999ab5b8ab607 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 23 Oct 2026 10:55:44 +0200 Subject: [PATCH 09/19] refactor(webdav): keep the Tika type default in the default config The catch-all was hidden in NewTika, so neither the yaml nor the env documentation showed it. It is a plain default now, like the CORS origins, and an empty list means what it says: nothing goes to Tika, and the server behind OC_TIKA_URL stays the search service's. --- services/webdav/README.md | 2 +- services/webdav/pkg/config/config.go | 2 +- services/webdav/pkg/config/defaults/defaultconfig.go | 2 ++ services/webdav/pkg/preprocessor/tika_test.go | 2 +- services/webdav/pkg/thumbnail/tika.go | 9 ++++----- services/webdav/pkg/thumbnail/tika_test.go | 8 +++++--- 6 files changed, 14 insertions(+), 11 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index ff2c9ddee2..6a1445736c 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,7 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika, which is what the default `*` in `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) says. That setting restricts it to a list of mime types instead, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index f4a8d261fc..d71b09f9a3 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -29,7 +29,7 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. Empty means all types that are not handled directly. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. The default, a single '*', sends every type that is not handled directly and lets Tika decide; an empty list sends nothing, which leaves the Tika server behind OC_TIKA_URL to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` } diff --git a/services/webdav/pkg/config/defaults/defaultconfig.go b/services/webdav/pkg/config/defaults/defaultconfig.go index f62e22a0a1..c668cbb211 100644 --- a/services/webdav/pkg/config/defaults/defaultconfig.go +++ b/services/webdav/pkg/config/defaults/defaultconfig.go @@ -44,6 +44,8 @@ func DefaultConfig() *config.Config { WebdavNamespace: "/users/{{.Id.OpaqueId}}", RevaGateway: shared.DefaultRevaConfig().Address, + TikaThumbnailMimeTypes: []string{"*"}, + Thumbnails: config.Thumbnails{ GeneratorURL: "http://127.0.0.1:9186", GeneratorTimeout: "30s", diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index c86822c556..4b1c86c484 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -139,7 +139,7 @@ var _ = Describe("TikaThumbnail", func() { var _ = Describe("ForType with a Tika server", func() { It("routes everything Tika is asked for to Tika, text and gif stay native", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", nil), Filename: "song.mp3"} + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"*"}), Filename: "song.mp3"} Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/vnd.geogebra.slides", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index 68a3ccd94e..91dafd0af6 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -7,14 +7,15 @@ import ( // Tika is the configured Tika server: its URL and the types it is asked for. // It only decides which file goes there, the call lives in the preprocessor. -// By default every non-image file is sent and Tika decides. +// The default list is a single "*", so every non-image file is sent and Tika +// decides; a list that names types restricts it, an empty one sends nothing. type Tika struct { URL string // our mime type -> Tika's, "" when equal; "*" means every type mimeTypes map[string]string } -// NewTika parses "mime[:tika-mime]" entries; empty means every type. +// NewTika parses "mime[:tika-mime]" entries, "*" being every type. func NewTika(url string, mimeTypes []string) Tika { t := Tika{URL: url, mimeTypes: map[string]string{}} for _, entry := range mimeTypes { @@ -23,9 +24,7 @@ func NewTika(url string, mimeTypes []string) Tika { t.mimeTypes[ours] = strings.TrimSpace(theirs) } } - if len(t.mimeTypes) == 0 { - t.mimeTypes["*"] = "" - } + return t } diff --git a/services/webdav/pkg/thumbnail/tika_test.go b/services/webdav/pkg/thumbnail/tika_test.go index 47f4151d84..313b95a286 100644 --- a/services/webdav/pkg/thumbnail/tika_test.go +++ b/services/webdav/pkg/thumbnail/tika_test.go @@ -9,7 +9,8 @@ import ( var _ = Describe("Tika", func() { none := thumbnail.NewTika("", nil) - all := thumbnail.NewTika("http://tika:9998", nil) + all := thumbnail.NewTika("http://tika:9998", []string{"*"}) + nothing := thumbnail.NewTika("http://tika:9998", nil) some := thumbnail.NewTika("http://tika:9998", []string{" Application/PDF ", "audio/mpeg", "image/x-nikon-nef:image/x-raw-nikon"}) DescribeTable("Supports", @@ -17,7 +18,8 @@ var _ = Describe("Tika", func() { Expect(tika.Supports(mimeType)).To(Equal(want)) }, Entry("nothing without a server", none, "application/pdf", false), - Entry("everything by default", all, "application/x-anything; charset=binary", true), + Entry("nothing with an empty list", nothing, "application/pdf", false), + Entry("everything with the default list", all, "application/x-anything; charset=binary", true), Entry("but no directories", all, "httpd/unix-directory", false), Entry("nor an unparsable type", all, "not a mime", false), Entry("a listed type", some, "application/pdf", true), @@ -32,6 +34,6 @@ var _ = Describe("Tika", func() { }, Entry("maps a type to the one Tika knows", some, "image/x-nikon-nef", "image/x-raw-nikon"), Entry("passes an unmapped type through, without parameters", some, "application/pdf; charset=binary", "application/pdf"), - Entry("passes everything through by default", all, "audio/mpeg", "audio/mpeg"), + Entry("passes everything through with the default list", all, "audio/mpeg", "audio/mpeg"), ) }) From 92dab13caa04be86c161b234fa4f9f11bc41a6f8 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 23 Oct 2026 11:07:12 +0200 Subject: [PATCH 10/19] docs(webdav): say what the Tika type hint is for The type decides which parser reads the file, so a raw photo that Tika only detected as a plain tiff is parsed as a tiff and its embedded preview is never found. No shipped format needs the hint, which is why the knob reads like dead code and has to say that it is not. --- services/webdav/README.md | 2 +- services/webdav/pkg/config/config.go | 2 +- services/webdav/pkg/thumbnail/tika.go | 13 ++++++++++--- services/webdav/pkg/thumbnail/tika_test.go | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index 6a1445736c..89f9bed07c 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,7 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika, which is what the default `*` in `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) says. That setting restricts it to a list of mime types instead, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika, which is what the default `*` in `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) says. That setting restricts it to a list of mime types instead, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats listed above are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index d71b09f9a3..de5628538f 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -29,7 +29,7 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. The default, a single '*', sends every type that is not handled directly and lets Tika decide; an empty list sends nothing, which leaves the Tika server behind OC_TIKA_URL to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. The default, a single '*', sends every type that is not handled directly and lets Tika decide; an empty list sends nothing, which leaves the Tika server behind OC_TIKA_URL to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` } diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index 91dafd0af6..0becb9b311 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -62,9 +62,16 @@ func (t Tika) ConfiguredFor(mimeType string) bool { } // ContentType is the type Tika is told, mapped where configured. Tika takes a -// declared type only when it refines what it detected itself, so a mapping pins -// a subtype its detector left at the parent type, a raw photo it only read as a -// tiff. It cannot overrule a type Tika detected. +// declared type only when it refines what it detected itself, so a mapping +// cannot overrule it; what it can do is pin the leaf type a detector left at +// the parent, a raw photo it only read as a plain tiff. +// +// That is the point of the mapping, and it is worth keeping even while nothing +// uses it: the type decides which parser reads the file, so a raw read as a +// tiff is parsed as a tiff, its maker notes stay unread, and the embedded +// preview the thumbnail is made of is never found. Every raw format shipped +// here is detected down to the leaf type today, so no entry is needed; the next +// format whose detection stops one level short needs exactly this. func (t Tika) ContentType(mimeType string) string { m, _, err := mime.ParseMediaType(mimeType) if err != nil { diff --git a/services/webdav/pkg/thumbnail/tika_test.go b/services/webdav/pkg/thumbnail/tika_test.go index 313b95a286..7cdad6b4fa 100644 --- a/services/webdav/pkg/thumbnail/tika_test.go +++ b/services/webdav/pkg/thumbnail/tika_test.go @@ -32,7 +32,7 @@ var _ = Describe("Tika", func() { func(tika thumbnail.Tika, mimeType, want string) { Expect(tika.ContentType(mimeType)).To(Equal(want)) }, - Entry("maps a type to the one Tika knows", some, "image/x-nikon-nef", "image/x-raw-nikon"), + Entry("pins the leaf type, so the detector does not stop at tiff and lose the embedded preview", some, "image/x-nikon-nef", "image/x-raw-nikon"), Entry("passes an unmapped type through, without parameters", some, "application/pdf; charset=binary", "application/pdf"), Entry("passes everything through with the default list", all, "audio/mpeg", "audio/mpeg"), ) From ff964dcc22748951b1df250f15eb0fa827373748 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 23 Oct 2026 12:27:00 +0200 Subject: [PATCH 11/19] refactor(webdav): ask who can serve a type, not what the type is called ForType decided by the name of the type: anything starting with image/ was handed to the generator, and no converter meant handing it over as well. A camera raw is an image by that rule, so it travelled to a generator that cannot read it, and an announced pdf travelled there too. It now asks in one order who claims the file: a type the Tika list names, an image the generator reads, a converter here, a catch-all, and otherwise nobody, which answers 404 before the file is read at all. The Tika list carries the formats a release serves a thumbnail for, the camera raws among them, and the default config hands it in, so an empty list still means nothing goes to Tika and a shared server stays the search service's. OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES adds to it. --- services/webdav/README.md | 2 +- services/webdav/pkg/config/config.go | 5 +- .../pkg/config/defaults/defaultconfig.go | 3 +- .../webdav/pkg/preprocessor/preprocessor.go | 65 ++++++++++-------- .../pkg/preprocessor/preprocessor_test.go | 12 +++- services/webdav/pkg/preprocessor/tika_test.go | 33 ++++++++-- services/webdav/pkg/service/v0/service.go | 2 +- services/webdav/pkg/thumbnail/sourcetypes.go | 16 +++++ .../webdav/pkg/thumbnail/sourcetypes_test.go | 32 +++++++++ services/webdav/pkg/thumbnail/tika.go | 66 +++++++++++++++++-- services/webdav/pkg/thumbnail/tika_test.go | 26 ++++++-- .../webdav/pkg/thumbnail/workflow/workflow.go | 9 ++- 12 files changed, 221 insertions(+), 50 deletions(-) create mode 100644 services/webdav/pkg/thumbnail/sourcetypes_test.go diff --git a/services/webdav/README.md b/services/webdav/README.md index 89f9bed07c..258b3a1ce1 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,7 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika, which is what the default `*` in `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) says. That setting restricts it to a list of mime types instead, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats listed above are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Which types go there is a list, and the default is the formats a Tika release serves a thumbnail for: documents, ebooks, office and iWork files, audio cover art and the camera raws. `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) replaces that list, `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES` adds to it, a single `*` in either sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika server shared with the search service to the search service alone. An entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats in the default list are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. Who gets a file is decided in one order, first match wins: a type the Tika list names goes to Tika, which is why the camera raws are named there, reva types them as images and no generator reads them; then an image the generator reads is handed over as it is, and for an image type that is what `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` says, an imagor with ImageMagick reads heic where the built-in one does not; then the built-in extractors take text, audio and GeoGebra; then a `*` takes whatever is left. A type nothing claims answers `404` without reading the file at all. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index de5628538f..bb5f997e57 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -28,8 +28,9 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` - TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"Restrict thumbnail generation via Tika to these mime types. The default, a single '*', sends every type that is not handled directly and lets Tika decide; an empty list sends nothing, which leaves the Tika server behind OC_TIKA_URL to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` + TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. The camera raws are in that list because reva types them as images and an image is handed to the generator as it is unless something claims it. A single '*' sends every type that nothing else claims, an empty list leaves the built-in list in place. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` + AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail, on top of the built-in list or of whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. An entry carries a type hint the same way." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` } diff --git a/services/webdav/pkg/config/defaults/defaultconfig.go b/services/webdav/pkg/config/defaults/defaultconfig.go index c668cbb211..6706199fb8 100644 --- a/services/webdav/pkg/config/defaults/defaultconfig.go +++ b/services/webdav/pkg/config/defaults/defaultconfig.go @@ -7,6 +7,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/shared" "github.com/opencloud-eu/opencloud/pkg/structs" "github.com/opencloud-eu/opencloud/services/webdav/pkg/config" + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" ) // FullDefaultConfig returns a fully initialized default configuration @@ -44,7 +45,7 @@ func DefaultConfig() *config.Config { WebdavNamespace: "/users/{{.Id.OpaqueId}}", RevaGateway: shared.DefaultRevaConfig().Address, - TikaThumbnailMimeTypes: []string{"*"}, + TikaThumbnailMimeTypes: thumbnail.DefaultTikaTypes, Thumbnails: config.Thumbnails{ GeneratorURL: "http://127.0.0.1:9186", diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index 41953c9264..1003a7f832 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -362,6 +362,7 @@ type Options struct { FontFace *opentype.FaceOptions MaxImageSize uint64 Tika thumbnail.Tika + SourceTypes thumbnail.SourceTypes Filename string } @@ -374,11 +375,32 @@ func tikaOr(opts Options, mimeType string, fallback FileConverter) FileConverter return TikaThumbnail{tikaURL: opts.Tika.URL, filename: opts.Filename, contentType: opts.Tika.ContentType(mimeType)} } -// ForType returns the converter for the specified mimeType -func ForType(mimeType string, opts Options) FileConverter { - // We can ignore the error here because we parse it in IsMimeTypeSupported before and if it fails - // return the service call. So we should only get here when the mimeType parses fine. +// ForType says what has to happen to a file of this type before the generator +// sees it: a converter to run, nil when the generator reads the file as it is, +// and ErrNoThumbnail when nothing here can make an image of it. +// +// The order is the answer to two questions that look the same and are not, what +// a type is and who can serve it: +// 1. a type the configuration names for Tika goes to Tika, an image too, which +// is how a raw photo is extracted instead of being handed to a generator +// that cannot read it +// 2. an image the generator reads is handed over untouched +// 3. a type with a converter here is converted here +// 4. what is left goes to Tika when it was told to take everything +// 5. and otherwise nothing can make a preview of it +func ForType(mimeType string, opts Options) (FileConverter, error) { + // We can ignore the error here because the caller parses it as well, so we + // only get here when the mimeType parses fine. mimeType, _, _ = mime.ParseMediaType(mimeType) + + if opts.Tika.ConfiguredFor(mimeType) { + return tikaOr(opts, mimeType, nil), nil + } + + if opts.SourceTypes.GeneratorReads(mimeType) { + return nil, nil + } + switch mimeType { case "text/plain": fontFace := opts.FontFace @@ -396,28 +418,19 @@ func ForType(mimeType string, opts Options) FileConverter { // try to use the default font fontLoader, _ = NewFontLoader("", fontFace) } - return TxtToImageConverter{ - fontLoader: fontLoader, - } - case "application/vnd.geogebra.slides": - return tikaOr(opts, mimeType, GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}) - case "application/vnd.geogebra.pinboard": - return tikaOr(opts, mimeType, GgpDecoder{}) - case "audio/flac": - fallthrough - case "audio/mpeg": - fallthrough - case "audio/ogg": - return tikaOr(opts, mimeType, AudioDecoder{}) - default: - // an image reaches the generator as it is: it reads the common types and - // may read more, an imagor with ImageMagick reads heic where we do not. - // OC_TIKA_THUMBNAIL_MIME_TYPES is how a deployment hands an image type - // to Tika instead. - if strings.HasPrefix(mimeType, "image/") && !opts.Tika.ConfiguredFor(mimeType) { - return nil - } - return tikaOr(opts, mimeType, nil) + return TxtToImageConverter{fontLoader: fontLoader}, nil + case "application/vnd.geogebra.slides": + return tikaOr(opts, mimeType, GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}), nil + case "application/vnd.geogebra.pinboard": + return tikaOr(opts, mimeType, GgpDecoder{}), nil + case "audio/flac", "audio/mpeg", "audio/ogg": + return tikaOr(opts, mimeType, AudioDecoder{}), nil } + + if converter := tikaOr(opts, mimeType, nil); converter != nil { + return converter, nil + } + + return nil, ErrNoThumbnail } diff --git a/services/webdav/pkg/preprocessor/preprocessor_test.go b/services/webdav/pkg/preprocessor/preprocessor_test.go index bc9eedb8eb..436f738c58 100644 --- a/services/webdav/pkg/preprocessor/preprocessor_test.go +++ b/services/webdav/pkg/preprocessor/preprocessor_test.go @@ -181,8 +181,16 @@ var _ = Describe("preprocessor", func() { Expect(ForType("text/plain", Options{})).To(BeAssignableToTypeOf(TxtToImageConverter{})) }) - It("has no converter for an unknown type", func() { - Expect(ForType("unknown", Options{})).To(BeNil()) + It("refuses a type nothing here can read", func() { + converter, err := ForType("application/pdf", Options{}) + Expect(err).To(MatchError(ErrNoThumbnail), "without a Tika server nothing makes an image of a pdf") + Expect(converter).To(BeNil()) + }) + + It("refuses an image the generator does not read, instead of handing it over", func() { + converter, err := ForType("image/x-nikon-nef", Options{}) + Expect(err).To(MatchError(ErrNoThumbnail)) + Expect(converter).To(BeNil()) }) }) }) diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index 4b1c86c484..7f1ff9304d 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -138,26 +138,45 @@ var _ = Describe("TikaThumbnail", func() { }) var _ = Describe("ForType with a Tika server", func() { - It("routes everything Tika is asked for to Tika, text and gif stay native", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"*"}), Filename: "song.mp3"} + sourceTypes := thumbnail.NewSourceTypes(nil) + + It("sends what the list names to Tika, even an image, and leaves the generator its own", func() { + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, nil), SourceTypes: sourceTypes, Filename: "song.mp3"} Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/vnd.geogebra.slides", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{}), "a raw is named, so it is extracted instead of handed over") Expect(ForType("text/plain", opts)).To(BeAssignableToTypeOf(TxtToImageConverter{})) Expect(ForType("image/png", opts)).To(BeNil(), "the generator reads a png itself") - Expect(ForType("image/x-nikon-nef", opts)).To(BeNil(), "an image type the catch-all does not take, the generator may read it") + }) + + It("hands an image type the deployment announced to the generator", func() { + opts := Options{ + Tika: thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, nil), + SourceTypes: thumbnail.NewSourceTypes([]string{"image/heic"}), + } + Expect(ForType("image/heic", opts)).To(BeNil(), "a generator that reads heic is told so through the source types") + }) + + It("takes what nothing else claims when it is told to take everything", func() { + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"*"}, nil), SourceTypes: sourceTypes} + Expect(ForType("application/x-anything", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) + Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{}), "an image the generator does not read is not an exception") + Expect(ForType("image/jpeg", opts)).To(BeNil(), "but one it reads never travels to Tika") }) It("keeps the in-process converters without a Tika server", func() { Expect(ForType("audio/mpeg", Options{})).To(BeAssignableToTypeOf(AudioDecoder{})) Expect(ForType("application/vnd.geogebra.slides", Options{})).To(BeAssignableToTypeOf(GgsDecoder{})) - Expect(ForType("image/x-nikon-nef", Options{})).To(BeNil(), "an image reaches the generator undecoded") }) - It("follows a configured list and hands the mapped type to Tika", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"})} + It("hands the mapped type to Tika", func() { + opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"}, nil), SourceTypes: sourceTypes} Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(AudioDecoder{}), "not in the configured list") - Expect(ForType("image/x-nikon-nef", opts).(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon"), "a named image type does go to Tika") + + converter, err := ForType("image/x-nikon-nef", opts) + Expect(err).ToNot(HaveOccurred()) + Expect(converter.(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon")) }) }) diff --git a/services/webdav/pkg/service/v0/service.go b/services/webdav/pkg/service/v0/service.go index f75457df3b..0dea3ba24c 100644 --- a/services/webdav/pkg/service/v0/service.go +++ b/services/webdav/pkg/service/v0/service.go @@ -216,7 +216,7 @@ func newThumbnailWorkflow(conf *config.Config, sourceTypes thumbnail.SourceTypes workflow.WithMaxInputSize(maxInputSize), workflow.WithSizes(sizes), workflow.WithSourceTypes(sourceTypes), - workflow.WithTika(thumbnail.NewTika(conf.TikaURL, conf.TikaThumbnailMimeTypes)), + workflow.WithTika(thumbnail.NewTika(conf.TikaURL, conf.TikaThumbnailMimeTypes, conf.AdditionalTikaThumbnailMimeTypes)), workflow.WithFormats(formats), workflow.WithTypeMapping(typeMapping), workflow.WithWebdavNamespace(conf.WebdavNamespace), diff --git a/services/webdav/pkg/thumbnail/sourcetypes.go b/services/webdav/pkg/thumbnail/sourcetypes.go index 63d1ba0128..cdc11cf3c9 100644 --- a/services/webdav/pkg/thumbnail/sourcetypes.go +++ b/services/webdav/pkg/thumbnail/sourcetypes.go @@ -54,6 +54,22 @@ func NewSourceTypes(entries []string) SourceTypes { return t } +// GeneratorReads reports whether the generator is handed a file of this type as +// it is. Only images are, and which ones is what the source types say: the +// built-in list is what both resize backends read, a deployment adds the types +// its own generator reads on top of it. +func (t SourceTypes) GeneratorReads(contentType string) bool { + parsed, _, err := mime.ParseMediaType(contentType) + if err != nil || !strings.HasPrefix(parsed, "image/") { + return false + } + if len(t.byType) == 0 { + return slices.Contains(GeneratorImageTypes, parsed) + } + + return t.Supports(parsed) +} + // Supports reports whether a preview is made of this type. func (t SourceTypes) Supports(contentType string) bool { parsed, _, err := mime.ParseMediaType(contentType) diff --git a/services/webdav/pkg/thumbnail/sourcetypes_test.go b/services/webdav/pkg/thumbnail/sourcetypes_test.go new file mode 100644 index 0000000000..26dee184dc --- /dev/null +++ b/services/webdav/pkg/thumbnail/sourcetypes_test.go @@ -0,0 +1,32 @@ +package thumbnail_test + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" +) + +var _ = Describe("SourceTypes", func() { + defaults := thumbnail.NewSourceTypes(nil) + withHeic := thumbnail.NewSourceTypes([]string{"image/heic"}) + + DescribeTable("GeneratorReads", + func(types thumbnail.SourceTypes, mimeType string, want bool) { + Expect(types.GeneratorReads(mimeType)).To(Equal(want)) + }, + Entry("an image both backends read", defaults, "image/jpeg", true), + Entry("with parameters", defaults, "image/png; charset=binary", true), + Entry("not a camera raw, which is an image nobody renders", defaults, "image/x-nikon-nef", false), + Entry("not a document, whatever the list says", defaults, "application/pdf", false), + Entry("not audio, which is announced but extracted", defaults, "audio/mpeg", false), + Entry("an image type the deployment added", withHeic, "image/heic", true), + Entry("and the built-in ones are still in there", withHeic, "image/tiff", true), + Entry("an unparsable type", defaults, "not a mime", false), + ) + + It("falls back to the built-in image types when nothing was configured", func() { + Expect(thumbnail.SourceTypes{}.GeneratorReads("image/jpeg")).To(BeTrue()) + Expect(thumbnail.SourceTypes{}.GeneratorReads("image/heic")).To(BeFalse()) + }) +}) diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index 0becb9b311..f8f892038e 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -2,23 +2,79 @@ package thumbnail import ( "mime" + "slices" "strings" ) +// DefaultTikaTypes are the types sent to a Tika server for their thumbnail, +// the formats a Tika release serves one for. The camera raws have to be named +// because reva types them as images, and an image is handed to the generator +// as it is unless something claims it. +var DefaultTikaTypes = []string{ + "application/pdf", + "application/epub+zip", + "application/vnd.ms-xpsdocument", + + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.ms-powerpoint", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.ms-excel", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.oasis.opendocument.text", + "application/vnd.oasis.opendocument.spreadsheet", + "application/vnd.oasis.opendocument.presentation", + "application/vnd.apple.pages", + "application/vnd.apple.numbers", + "application/vnd.apple.keynote", + + "application/vnd.geogebra.file", + "application/vnd.geogebra.slides", + "application/vnd.geogebra.pinboard", + + "audio/flac", + "audio/mpeg", + "audio/ogg", + "audio/x-flac", + "audio/x-m4a", + + "application/x-msdownload", + + "image/x-adobe-dng", + "image/x-canon-cr2", + "image/x-canon-crw", + "image/x-epson-erf", + "image/x-fuji-raf", + "image/x-kodak-dcr", + "image/x-kodak-kdc", + "image/x-minolta-mrw", + "image/x-nikon-nef", + "image/x-nikon-nrw", + "image/x-olympus-orf", + "image/x-panasonic-raw", + "image/x-panasonic-rw2", + "image/x-pentax-pef", + "image/x-sigma-x3f", + "image/x-sony-arw", + "image/x-sony-sr2", + "image/x-sony-srf", +} + // Tika is the configured Tika server: its URL and the types it is asked for. // It only decides which file goes there, the call lives in the preprocessor. -// The default list is a single "*", so every non-image file is sent and Tika -// decides; a list that names types restricts it, an empty one sends nothing. type Tika struct { URL string // our mime type -> Tika's, "" when equal; "*" means every type mimeTypes map[string]string } -// NewTika parses "mime[:tika-mime]" entries, "*" being every type. -func NewTika(url string, mimeTypes []string) Tika { +// NewTika parses "mime[:tika-mime]" entries. mimeTypes is the configured list, +// which the default config fills with DefaultTikaTypes, additional adds to it, +// and "*" in either sends every type that nothing else claims. An empty list +// sends nothing, which leaves a shared Tika server to the search service. +func NewTika(url string, mimeTypes, additional []string) Tika { t := Tika{URL: url, mimeTypes: map[string]string{}} - for _, entry := range mimeTypes { + for _, entry := range slices.Concat(mimeTypes, additional) { ours, theirs, _ := strings.Cut(strings.ToLower(strings.TrimSpace(entry)), ":") if ours = strings.TrimSpace(ours); ours != "" { t.mimeTypes[ours] = strings.TrimSpace(theirs) diff --git a/services/webdav/pkg/thumbnail/tika_test.go b/services/webdav/pkg/thumbnail/tika_test.go index 7cdad6b4fa..6feef7cbd5 100644 --- a/services/webdav/pkg/thumbnail/tika_test.go +++ b/services/webdav/pkg/thumbnail/tika_test.go @@ -8,10 +8,13 @@ import ( ) var _ = Describe("Tika", func() { - none := thumbnail.NewTika("", nil) - all := thumbnail.NewTika("http://tika:9998", []string{"*"}) - nothing := thumbnail.NewTika("http://tika:9998", nil) - some := thumbnail.NewTika("http://tika:9998", []string{" Application/PDF ", "audio/mpeg", "image/x-nikon-nef:image/x-raw-nikon"}) + none := thumbnail.NewTika("", thumbnail.DefaultTikaTypes, nil) + all := thumbnail.NewTika("http://tika:9998", []string{"*"}, nil) + nothing := thumbnail.NewTika("http://tika:9998", nil, nil) + some := thumbnail.NewTika("http://tika:9998", []string{" Application/PDF ", "audio/mpeg", "image/x-nikon-nef:image/x-raw-nikon"}, nil) + built := thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, nil) + extended := thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, []string{"application/zip", "image/heic"}) + extendedAll := thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, []string{"*"}) DescribeTable("Supports", func(tika thumbnail.Tika, mimeType string, want bool) { @@ -26,6 +29,21 @@ var _ = Describe("Tika", func() { Entry("a listed type with parameters", some, "audio/mpeg; charset=binary", true), Entry("a mapped type", some, "image/x-nikon-nef", true), Entry("an unlisted type", some, "application/zip", false), + Entry("a document from the built-in list", built, "application/pdf", true), + Entry("a camera raw from the built-in list, which is why it is named there", built, "image/x-nikon-nef", true), + Entry("but not a type the built-in list leaves alone", built, "application/zip", false), + Entry("a type the additional list adds", extended, "application/zip", true), + Entry("while the built-in list is still in effect", extended, "application/pdf", true), + Entry("and a catch-all in the additional list takes the rest", extendedAll, "application/x-anything", true), + ) + + DescribeTable("ConfiguredFor", + func(tika thumbnail.Tika, mimeType string, want bool) { + Expect(tika.ConfiguredFor(mimeType)).To(Equal(want)) + }, + Entry("a named type", built, "image/x-nikon-nef", true), + Entry("not a type the catch-all takes", all, "application/pdf", false), + Entry("not an unnamed type", built, "application/zip", false), ) DescribeTable("ContentType", diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 5a9c7ba5fc..d76a3ec656 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -554,12 +554,19 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta // the preprocessor decides what a type needs. No converter means the file // is handed to the generator as it is, which is the case for every type it // reads itself. - converter := preprocessor.ForType(mimeType, preprocessor.Options{ + converter, err := preprocessor.ForType(mimeType, preprocessor.Options{ FontMapFile: w.fontMapFile, MaxImageSize: w.maxInputSize, Tika: w.tika, + SourceTypes: w.sourceTypes, Filename: filename, }) + if err != nil { + // nothing can make an image of this type, so there is nothing to fetch + logger.Debug().Str("mimetype", mimeType).Msg("no preview for this type") + + return nil, "", nil, ErrNoThumbnail + } // what the extraction found is remembered per file, so a second size does // not send the file to Tika again, and a file that carries nothing is only From f2a15e94345b2e823e57e979aa9e1d11ed8743f8 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 23 Oct 2026 14:00:28 +0200 Subject: [PATCH 12/19] docs: correct what an empty Tika type list does, and couple the two ceilings in writing The description said an empty list leaves the built-in list in place, which is what an unset variable does; an explicitly empty one sends nothing. And a ladder that reaches past the generator's output ceiling asks for a box the generator refuses, which nothing checks for us, so the thumbnails README says it. --- services/thumbnails/README.md | 2 ++ services/webdav/pkg/config/config.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/thumbnails/README.md b/services/thumbnails/README.md index fc59f311fc..a652b797d7 100644 --- a/services/thumbnails/README.md +++ b/services/thumbnails/README.md @@ -102,6 +102,8 @@ webdav decides which size is asked for, keeps the thumbnail cache and holds the The source and the thumbnail have ceilings of their own, for different reasons. How large a preview may be is webdav's decision, and its largest configured resolution is what it ever asks for; `THUMBNAILS_MAX_OUTPUT_*` is the net under that for anything else reaching this endpoint, because `fill` and `stretch` enlarge a small source to fill the box. How large a source may be is this service's decision, since it is the one that sees the pixels: webdav knows a file's type, size and checksum, not its dimensions. +The two sides are configured apart and nothing couples them, so a ladder that reaches past `THUMBNAILS_MAX_OUTPUT_WIDTH` or `THUMBNAILS_MAX_OUTPUT_HEIGHT` asks for a box this endpoint refuses, and the rung above the ceiling answers with an error rather than an image. A deployment that raises `WEBDAV_THUMBNAILS_RESOLUTIONS` past 2048 has to raise the ceiling with it. + A real imagor has one pair of knobs for both, `-vips-max-width` and `-vips-max-height`, which bound every image in its pipeline, the loaded source as well as the result. Set them to the source ceiling. They are also more forgiving than this service for formats libvips can shrink while loading: a 9000 pixel wide JPEG passes a 2048 limit there, where this service refuses it on the header. ## Supported Formats diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index bb5f997e57..8d664df4be 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -29,7 +29,7 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. The camera raws are in that list because reva types them as images and an image is handed to the generator as it is unless something claims it. A single '*' sends every type that nothing else claims, an empty list leaves the built-in list in place. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. The camera raws are in that list because reva types them as images and an image is handed to the generator as it is unless something claims it. A single '*' sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika shared with the search service to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail, on top of the built-in list or of whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. An entry carries a type hint the same way." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` From d326bbd54fc7ce734eb16ae6ecf424c41f2da6a7 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Tue, 3 Nov 2026 13:55:56 +0100 Subject: [PATCH 13/19] fix(webdav): send m4b audiobooks to Tika for their cover --- services/webdav/pkg/thumbnail/tika.go | 1 + 1 file changed, 1 insertion(+) diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index f8f892038e..93be89437e 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -37,6 +37,7 @@ var DefaultTikaTypes = []string{ "audio/ogg", "audio/x-flac", "audio/x-m4a", + "audio/x-m4b", "application/x-msdownload", From 82735a337d71b456a79506c3ac4daa415215c80b Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Wed, 4 Nov 2026 12:50:19 +0100 Subject: [PATCH 14/19] fix(webdav): give every thumbnail type exactly one taker A named Tika type goes to Tika, then the built-in converters, then images to the generator, then the rest to Tika under "*" or to the generator. "*" never sends an image, which only moved the file to come back empty, and an announced type without a converter reaches the generator again, as it does on main since the generator pass-through. --- services/webdav/README.md | 10 ++- services/webdav/pkg/config/config.go | 6 +- .../webdav/pkg/preprocessor/preprocessor.go | 57 ++++++++-------- .../pkg/preprocessor/preprocessor_test.go | 14 +--- services/webdav/pkg/preprocessor/tika_test.go | 67 +++++++++---------- services/webdav/pkg/thumbnail/sourcetypes.go | 21 +----- .../webdav/pkg/thumbnail/sourcetypes_test.go | 14 ++-- services/webdav/pkg/thumbnail/tika.go | 18 +++-- .../webdav/pkg/thumbnail/workflow/workflow.go | 27 +++----- 9 files changed, 105 insertions(+), 129 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index 258b3a1ce1..31391931e7 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,7 +10,15 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Which types go there is a list, and the default is the formats a Tika release serves a thumbnail for: documents, ebooks, office and iWork files, audio cover art and the camera raws. `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) replaces that list, `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES` adds to it, a single `*` in either sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika server shared with the search service to the search service alone. An entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats in the default list are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. Who gets a file is decided in one order, first match wins: a type the Tika list names goes to Tika, which is why the camera raws are named there, reva types them as images and no generator reads them; then an image the generator reads is handed over as it is, and for an image type that is what `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` says, an imagor with ImageMagick reads heic where the built-in one does not; then the built-in extractors take text, audio and GeoGebra; then a `*` takes whatever is left. A type nothing claims answers `404` without reading the file at all. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. +When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Which types go there is a list, and the default is the formats a Tika release serves a thumbnail for: documents, ebooks, office and iWork files, audio cover art and the camera raws. `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) replaces that list, `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES` adds to it, a single `*` in either sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika server shared with the search service to the search service alone. An entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats in the default list are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. Who gets a file is decided in one order, first match wins, and every type has exactly one taker: + +1. a type the Tika list names goes to Tika, an image too, which is why the camera raws are named there: reva types them as images and no generator reads them +2. text, audio and GeoGebra go to the built-in extractors +3. an image goes to the generator as it is; whether it can read it is the generator's answer, an imagor with ImageMagick reads heic where the built-in one does not +4. anything else goes to Tika when the Tika list has `*` +5. and otherwise to the generator as it is + +So `*` never sends an image: images belong to the generator, and sending one to Tika would only move the file. An image type that only Tika can read has to be named in the Tika list. Announcing a type in `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` and sending it to Tika are separate decisions: the announcement is what `oc:has-preview` reports, the Tika list says who makes the image. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index 8d664df4be..bfdaea2c16 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -29,8 +29,8 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. The camera raws are in that list because reva types them as images and an image is handed to the generator as it is unless something claims it. A single '*' sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika shared with the search service to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` - AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail, on top of the built-in list or of whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. An entry carries a type hint the same way." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. A named type goes to Tika before anything else, an image too: the camera raws are in that list because reva types them as images and an image the list does not name goes to the generator. A single '*' sends every other type that is neither an image nor has a built-in converter, so it never sends an image, and an empty list sends nothing at all, which leaves a Tika shared with the search service to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` + AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail, on top of the built-in list or of whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. An entry carries a type hint the same way. An image type that only Tika can read has to be named here or there, '*' never sends an image." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` } @@ -54,7 +54,7 @@ type Thumbnails struct { CacheS3Endpoint string `yaml:"cache_s3_endpoint" env:"WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT" desc:"S3 endpoint URL (for MinIO or compatible services) when WEBDAV_THUMBNAILS_CACHE_BACKEND is 's3'." introductionVersion:"9.0.0"` CacheS3AccessKey string `yaml:"cache_s3_access_key" env:"WEBDAV_THUMBNAILS_CACHE_S3_ACCESS_KEY" desc:"S3 access key for thumbnail cache authentication." introductionVersion:"9.0.0"` CacheS3SecretKey string `yaml:"cache_s3_secret_key" env:"WEBDAV_THUMBNAILS_CACHE_S3_SECRET_KEY" desc:"S3 secret key for thumbnail cache authentication." introductionVersion:"9.0.0"` - AdditionalSourceTypes []string `yaml:"additional_source_types" env:"OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_SOURCE_TYPES" desc:"Additional mime types a preview is announced and attempted for, e.g. image/vnd.microsoft.icon for a generator that reads icons. The built-in list is included; this only adds to them. A type the running generator cannot read answers 404." introductionVersion:"9.0.0"` + AdditionalSourceTypes []string `yaml:"additional_source_types" env:"OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_SOURCE_TYPES" desc:"Additional mime types a preview is announced and attempted for, e.g. image/vnd.microsoft.icon for a generator that reads icons. The built-in list is included; this only adds to them. An announced type that the Tika list does not name and no built-in converter takes goes to the generator as it is, an image always and anything else unless the Tika list has '*'; a type the running generator cannot read answers 404. Announcing a type does not send it to Tika, naming it in the Tika list does." introductionVersion:"9.0.0"` AdditionalGeneratorFormats []string `yaml:"additional_generator_formats" env:"OC_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS;WEBDAV_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS" desc:"Additional formats the thumbnail generator writes, one per type it writes, as type:format entries, e.g. image/webp:webp. The format is the name the generator's own format filter uses. The built-in list is included; an entry for a type that is already listed replaces it. A type that is not listed is asked for as a JPEG instead, because what the generator behind the URL really writes is its own business." introductionVersion:"9.0.0"` AdditionalOutputTypes []string `yaml:"additional_output_types" env:"OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES;WEBDAV_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES" desc:"Additional types a thumbnail is returned in, one per type of the image it is made from, as source:target entries, e.g. image/vnd.microsoft.icon:image/png. The built-in list is included; an entry for a source type that is already listed replaces it. The target is asked for by the name WEBDAV_THUMBNAILS_ADDITIONAL_GENERATOR_FORMATS gives it. A type that is not listed becomes a JPEG; a target this service has no format name for is asked for as a JPEG as well." introductionVersion:"9.0.0"` diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index 1003a7f832..c5886ac35d 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -362,43 +362,36 @@ type Options struct { FontFace *opentype.FaceOptions MaxImageSize uint64 Tika thumbnail.Tika - SourceTypes thumbnail.SourceTypes Filename string } -// tikaOr prefers a configured Tika server, else the fallback -func tikaOr(opts Options, mimeType string, fallback FileConverter) FileConverter { - if !opts.Tika.Supports(mimeType) { - return fallback - } - +func toTika(opts Options, mimeType string) FileConverter { return TikaThumbnail{tikaURL: opts.Tika.URL, filename: opts.Filename, contentType: opts.Tika.ContentType(mimeType)} } // ForType says what has to happen to a file of this type before the generator -// sees it: a converter to run, nil when the generator reads the file as it is, -// and ErrNoThumbnail when nothing here can make an image of it. +// sees it: a converter to run, or nil when the file goes to the generator as it +// is, which answers whether it can read it. Only types that passed the gate +// get here: announced ones, and those the Tika list takes. // -// The order is the answer to two questions that look the same and are not, what -// a type is and who can serve it: -// 1. a type the configuration names for Tika goes to Tika, an image too, which -// is how a raw photo is extracted instead of being handed to a generator -// that cannot read it -// 2. an image the generator reads is handed over untouched -// 3. a type with a converter here is converted here +// Every type has exactly one taker, the first that applies: +// 1. a type the Tika list names goes to Tika, an image too, which is how a raw +// photo is extracted instead of being handed to a generator that cannot +// read it +// 2. a type with a converter here is converted here +// 3. an image goes to the generator // 4. what is left goes to Tika when it was told to take everything -// 5. and otherwise nothing can make a preview of it -func ForType(mimeType string, opts Options) (FileConverter, error) { +// 5. and otherwise to the generator +// +// So "*" never sends an image: images belong to the generator, and sending one +// to Tika would move the file for nothing. +func ForType(mimeType string, opts Options) FileConverter { // We can ignore the error here because the caller parses it as well, so we // only get here when the mimeType parses fine. mimeType, _, _ = mime.ParseMediaType(mimeType) if opts.Tika.ConfiguredFor(mimeType) { - return tikaOr(opts, mimeType, nil), nil - } - - if opts.SourceTypes.GeneratorReads(mimeType) { - return nil, nil + return toTika(opts, mimeType) } switch mimeType { @@ -419,18 +412,22 @@ func ForType(mimeType string, opts Options) (FileConverter, error) { fontLoader, _ = NewFontLoader("", fontFace) } - return TxtToImageConverter{fontLoader: fontLoader}, nil + return TxtToImageConverter{fontLoader: fontLoader} case "application/vnd.geogebra.slides": - return tikaOr(opts, mimeType, GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}), nil + return GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)} case "application/vnd.geogebra.pinboard": - return tikaOr(opts, mimeType, GgpDecoder{}), nil + return GgpDecoder{} case "audio/flac", "audio/mpeg", "audio/ogg": - return tikaOr(opts, mimeType, AudioDecoder{}), nil + return AudioDecoder{} } - if converter := tikaOr(opts, mimeType, nil); converter != nil { - return converter, nil + if strings.HasPrefix(mimeType, "image/") { + return nil } - return nil, ErrNoThumbnail + if opts.Tika.TakesAll() { + return toTika(opts, mimeType) + } + + return nil } diff --git a/services/webdav/pkg/preprocessor/preprocessor_test.go b/services/webdav/pkg/preprocessor/preprocessor_test.go index 436f738c58..08cffabb77 100644 --- a/services/webdav/pkg/preprocessor/preprocessor_test.go +++ b/services/webdav/pkg/preprocessor/preprocessor_test.go @@ -165,7 +165,7 @@ var _ = Describe("preprocessor", func() { }) Describe("ForType", func() { - It("has no converter for an image, which never reaches the preprocessor", func() { + It("hands an image to the generator as it is", func() { Expect(ForType("image/png", Options{})).To(BeNil()) }) @@ -181,16 +181,8 @@ var _ = Describe("preprocessor", func() { Expect(ForType("text/plain", Options{})).To(BeAssignableToTypeOf(TxtToImageConverter{})) }) - It("refuses a type nothing here can read", func() { - converter, err := ForType("application/pdf", Options{}) - Expect(err).To(MatchError(ErrNoThumbnail), "without a Tika server nothing makes an image of a pdf") - Expect(converter).To(BeNil()) - }) - - It("refuses an image the generator does not read, instead of handing it over", func() { - converter, err := ForType("image/x-nikon-nef", Options{}) - Expect(err).To(MatchError(ErrNoThumbnail)) - Expect(converter).To(BeNil()) + It("hands an announced type without a converter to the generator, which says whether it reads it", func() { + Expect(ForType("application/pdf", Options{})).To(BeNil()) }) }) }) diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index 7f1ff9304d..fee3aaa6e4 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -11,6 +11,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/onsi/gomega/types" "github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail" ) @@ -138,45 +139,43 @@ var _ = Describe("TikaThumbnail", func() { }) var _ = Describe("ForType with a Tika server", func() { - sourceTypes := thumbnail.NewSourceTypes(nil) + const tikaURL = "http://tika:9998" + named := thumbnail.NewTika(tikaURL, thumbnail.DefaultTikaTypes, nil) + everything := thumbnail.NewTika(tikaURL, []string{"*"}, nil) + off := thumbnail.NewTika("", thumbnail.DefaultTikaTypes, nil) - It("sends what the list names to Tika, even an image, and leaves the generator its own", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, nil), SourceTypes: sourceTypes, Filename: "song.mp3"} - Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("application/vnd.geogebra.slides", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{}), "a raw is named, so it is extracted instead of handed over") - Expect(ForType("text/plain", opts)).To(BeAssignableToTypeOf(TxtToImageConverter{})) - Expect(ForType("image/png", opts)).To(BeNil(), "the generator reads a png itself") - }) + tika := BeAssignableToTypeOf(TikaThumbnail{}) + generator := BeNil() - It("hands an image type the deployment announced to the generator", func() { - opts := Options{ - Tika: thumbnail.NewTika("http://tika:9998", thumbnail.DefaultTikaTypes, nil), - SourceTypes: thumbnail.NewSourceTypes([]string{"image/heic"}), - } - Expect(ForType("image/heic", opts)).To(BeNil(), "a generator that reads heic is told so through the source types") - }) + for _, c := range []struct { + name string + tika thumbnail.Tika + mimeType string + taker types.GomegaMatcher + }{ + {"a named document goes to Tika", named, "application/pdf", tika}, + {"a named image goes to Tika too", named, "image/x-nikon-nef", tika}, + {"a named type with a converter goes to Tika", named, "audio/mpeg", tika}, + {"a converter takes what the list does not name", named, "text/plain", BeAssignableToTypeOf(TxtToImageConverter{})}, + {"an image goes to the generator", named, "image/png", generator}, + {"an unnamed image goes to the generator", named, "image/heic", generator}, + {"an unnamed document goes to the generator", named, "application/x-anything", generator}, - It("takes what nothing else claims when it is told to take everything", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"*"}, nil), SourceTypes: sourceTypes} - Expect(ForType("application/x-anything", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("image/x-nikon-nef", opts)).To(BeAssignableToTypeOf(TikaThumbnail{}), "an image the generator does not read is not an exception") - Expect(ForType("image/jpeg", opts)).To(BeNil(), "but one it reads never travels to Tika") - }) + {"the catch-all takes a document", everything, "application/x-anything", tika}, + {"the catch-all never takes an image", everything, "image/x-nikon-nef", generator}, + {"nor a jpeg", everything, "image/jpeg", generator}, + {"nor what a converter takes", everything, "audio/mpeg", BeAssignableToTypeOf(AudioDecoder{})}, - It("keeps the in-process converters without a Tika server", func() { - Expect(ForType("audio/mpeg", Options{})).To(BeAssignableToTypeOf(AudioDecoder{})) - Expect(ForType("application/vnd.geogebra.slides", Options{})).To(BeAssignableToTypeOf(GgsDecoder{})) - }) + {"without a Tika URL nothing goes to Tika", off, "application/pdf", generator}, + {"and the converters are back", off, "application/vnd.geogebra.slides", BeAssignableToTypeOf(GgsDecoder{})}, + } { + It(c.name, func() { + Expect(ForType(c.mimeType, Options{Tika: c.tika})).To(c.taker) + }) + } It("hands the mapped type to Tika", func() { - opts := Options{Tika: thumbnail.NewTika("http://tika:9998", []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"}, nil), SourceTypes: sourceTypes} - Expect(ForType("application/pdf", opts)).To(BeAssignableToTypeOf(TikaThumbnail{})) - Expect(ForType("audio/mpeg", opts)).To(BeAssignableToTypeOf(AudioDecoder{}), "not in the configured list") - - converter, err := ForType("image/x-nikon-nef", opts) - Expect(err).ToNot(HaveOccurred()) - Expect(converter.(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon")) + t := thumbnail.NewTika(tikaURL, []string{"application/pdf", "image/x-nikon-nef:image/x-raw-nikon"}, nil) + Expect(ForType("image/x-nikon-nef", Options{Tika: t}).(TikaThumbnail).contentType).To(Equal("image/x-raw-nikon")) }) }) diff --git a/services/webdav/pkg/thumbnail/sourcetypes.go b/services/webdav/pkg/thumbnail/sourcetypes.go index cdc11cf3c9..566162064b 100644 --- a/services/webdav/pkg/thumbnail/sourcetypes.go +++ b/services/webdav/pkg/thumbnail/sourcetypes.go @@ -6,9 +6,8 @@ import ( "strings" ) -// GeneratorImageTypes are the image types both resize backends read, so webdav -// hands the file to the generator as it is. Every other type needs something to -// make an image of it first, a preprocessor here or a Tika server. +// GeneratorImageTypes are the image types both resize backends read, announced +// without further configuration. var GeneratorImageTypes = []string{ "image/png", "image/jpg", @@ -54,22 +53,6 @@ func NewSourceTypes(entries []string) SourceTypes { return t } -// GeneratorReads reports whether the generator is handed a file of this type as -// it is. Only images are, and which ones is what the source types say: the -// built-in list is what both resize backends read, a deployment adds the types -// its own generator reads on top of it. -func (t SourceTypes) GeneratorReads(contentType string) bool { - parsed, _, err := mime.ParseMediaType(contentType) - if err != nil || !strings.HasPrefix(parsed, "image/") { - return false - } - if len(t.byType) == 0 { - return slices.Contains(GeneratorImageTypes, parsed) - } - - return t.Supports(parsed) -} - // Supports reports whether a preview is made of this type. func (t SourceTypes) Supports(contentType string) bool { parsed, _, err := mime.ParseMediaType(contentType) diff --git a/services/webdav/pkg/thumbnail/sourcetypes_test.go b/services/webdav/pkg/thumbnail/sourcetypes_test.go index 26dee184dc..042abb7d3a 100644 --- a/services/webdav/pkg/thumbnail/sourcetypes_test.go +++ b/services/webdav/pkg/thumbnail/sourcetypes_test.go @@ -11,22 +11,16 @@ var _ = Describe("SourceTypes", func() { defaults := thumbnail.NewSourceTypes(nil) withHeic := thumbnail.NewSourceTypes([]string{"image/heic"}) - DescribeTable("GeneratorReads", + DescribeTable("Supports", func(types thumbnail.SourceTypes, mimeType string, want bool) { - Expect(types.GeneratorReads(mimeType)).To(Equal(want)) + Expect(types.Supports(mimeType)).To(Equal(want)) }, Entry("an image both backends read", defaults, "image/jpeg", true), Entry("with parameters", defaults, "image/png; charset=binary", true), - Entry("not a camera raw, which is an image nobody renders", defaults, "image/x-nikon-nef", false), - Entry("not a document, whatever the list says", defaults, "application/pdf", false), - Entry("not audio, which is announced but extracted", defaults, "audio/mpeg", false), + Entry("built-in audio", defaults, "audio/mpeg", true), + Entry("not a camera raw by default", defaults, "image/x-nikon-nef", false), Entry("an image type the deployment added", withHeic, "image/heic", true), Entry("and the built-in ones are still in there", withHeic, "image/tiff", true), Entry("an unparsable type", defaults, "not a mime", false), ) - - It("falls back to the built-in image types when nothing was configured", func() { - Expect(thumbnail.SourceTypes{}.GeneratorReads("image/jpeg")).To(BeTrue()) - Expect(thumbnail.SourceTypes{}.GeneratorReads("image/heic")).To(BeFalse()) - }) }) diff --git a/services/webdav/pkg/thumbnail/tika.go b/services/webdav/pkg/thumbnail/tika.go index 93be89437e..d0e7ca22ff 100644 --- a/services/webdav/pkg/thumbnail/tika.go +++ b/services/webdav/pkg/thumbnail/tika.go @@ -101,10 +101,9 @@ func (t Tika) Supports(mimeType string) bool { return all } -// ConfiguredFor reports whether OC_TIKA_THUMBNAIL_MIME_TYPES lists this type, -// as opposed to the catch-all taking it. An image is only taken away from the -// generator when the configuration asks for it, because the generator may well -// read the type itself. +// ConfiguredFor reports whether the Tika list names this type, as opposed to +// the catch-all taking it. Only a named type is taken away from a converter or +// the generator. func (t Tika) ConfiguredFor(mimeType string) bool { if t.URL == "" { return false @@ -118,6 +117,17 @@ func (t Tika) ConfiguredFor(mimeType string) bool { return named } +// TakesAll reports whether the Tika list has the catch-all "*", which takes +// every announced type that is neither an image nor has a converter. +func (t Tika) TakesAll() bool { + if t.URL == "" { + return false + } + _, all := t.mimeTypes["*"] + + return all +} + // ContentType is the type Tika is told, mapped where configured. Tika takes a // declared type only when it refines what it detected itself, so a mapping // cannot overrule it; what it can do is pin the leaf type a detector left at diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index d76a3ec656..568fd46105 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -488,10 +488,9 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R } } - // Produce the source image to send to the generator, never decoding an image - // in webdav: real images (incl. gif) are streamed straight through undecoded; - // non-image sources are converted to image bytes here so the generator always - // receives an image. + // Produce the source to send to the generator, never decoding an image in + // webdav: what Tika or a converter here takes is turned into image bytes, the + // rest is streamed straight through undecoded. imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, checksum, logger) if err != nil { if errors.Is(err, ErrNoThumbnail) { @@ -543,30 +542,24 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R // sourceImage returns a reader over the source to send to the generator, plus a // cleanup func to release any resources (download body, temp buffer). It never // decodes an image in webdav: -// - a type without a converter (image/*, incl. gif, and whatever else the source -// types announce) is streamed straight through from storage undecoded; the -// generator decides whether it can read it. -// - text/plain is rendered to an image here (the only true conversion). -// - audio and geogebra sources have their embedded image extracted to bytes. +// - a type preprocessor.ForType gives no converter (images, and whatever else +// is announced and not taken by Tika) is streamed straight through from +// storage undecoded; the generator decides whether it can read it. +// - a type Tika takes has its image extracted there. +// - text/plain is rendered to an image here, audio and geogebra sources have +// their embedded image extracted to bytes. func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename, checksum string, logger log.Logger) (io.Reader, string, func(), error) { m, _, _ := mime.ParseMediaType(mimeType) // the preprocessor decides what a type needs. No converter means the file // is handed to the generator as it is, which is the case for every type it // reads itself. - converter, err := preprocessor.ForType(mimeType, preprocessor.Options{ + converter := preprocessor.ForType(mimeType, preprocessor.Options{ FontMapFile: w.fontMapFile, MaxImageSize: w.maxInputSize, Tika: w.tika, - SourceTypes: w.sourceTypes, Filename: filename, }) - if err != nil { - // nothing can make an image of this type, so there is nothing to fetch - logger.Debug().Str("mimetype", mimeType).Msg("no preview for this type") - - return nil, "", nil, ErrNoThumbnail - } // what the extraction found is remembered per file, so a second size does // not send the file to Tika again, and a file that carries nothing is only From 3716c657046077fc7fb0a0a0c02e66855ca3feae Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 6 Nov 2026 12:00:12 +0100 Subject: [PATCH 15/19] fix(webdav): cache a file the built-in extractors find no image in, as for Tika --- services/webdav/pkg/preprocessor/errors.go | 8 +-- .../webdav/pkg/preprocessor/preprocessor.go | 16 +++--- .../pkg/preprocessor/preprocessor_test.go | 54 +++++++++++++++++-- services/webdav/pkg/preprocessor/tika_test.go | 2 +- 4 files changed, 59 insertions(+), 21 deletions(-) diff --git a/services/webdav/pkg/preprocessor/errors.go b/services/webdav/pkg/preprocessor/errors.go index a0db070da5..45baa493ce 100644 --- a/services/webdav/pkg/preprocessor/errors.go +++ b/services/webdav/pkg/preprocessor/errors.go @@ -2,10 +2,4 @@ package preprocessor import "errors" -var ( - ErrNoImageFromAudioFile = errors.New("preprocessor: could not extract image from audio file") - ErrNoConverterForExtractedImageFromGgsFile = errors.New("preprocessor: could not find converter for image extracted from ggs file") - ErrNoConverterForExtractedImageFromAudioFile = errors.New("preprocessor: could not find converter for image extracted from audio file") - ErrNoConverterForExtractedImageFromGgpFile = errors.New("preprocessor: could not find converter for image extracted from ggp file") - ErrNoThumbnail = errors.New("preprocessor: the document has no thumbnail") -) +var ErrNoThumbnail = errors.New("preprocessor: the document has no thumbnail") diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index c5886ac35d..607ead90e7 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -86,7 +86,7 @@ func (g GgsDecoder) Convert(r io.Reader) (*Image, error) { return &Image{ContentType: "image/png", Data: data}, nil } } - return nil, errors.Errorf("%s not found", g.thumbnailpath) + return nil, ErrNoThumbnail } // AudioDecoder is a converter for the audio file. @@ -111,12 +111,8 @@ func (i AudioDecoder) Convert(r io.Reader) (*Image, error) { } picture := m.Picture() - if picture == nil { - return nil, ErrNoImageFromAudioFile - } - - if !strings.HasPrefix(picture.MIMEType, "image/") { - return nil, ErrNoConverterForExtractedImageFromAudioFile + if picture == nil || !strings.HasPrefix(picture.MIMEType, "image/") { + return nil, ErrNoThumbnail } return &Image{ContentType: picture.MIMEType, Data: picture.Data}, nil @@ -260,7 +256,7 @@ func (j GgpDecoder) Convert(r io.Reader) (*Image, error) { contentType := http.DetectContentType(b) if !strings.HasPrefix(contentType, "image/") { - return nil, ErrNoConverterForExtractedImageFromGgpFile + return nil, ErrNoThumbnail } return &Image{ContentType: contentType, Data: b}, nil @@ -268,12 +264,12 @@ func (j GgpDecoder) Convert(r io.Reader) (*Image, error) { func extractBase64ImageFromGGP(ggp *GGPStruct) (string, error) { if len(ggp.Sections) < 1 || len(ggp.Sections[0].Cards) < 1 { - return "", errors.New("cant find thumbnail in ggp file") + return "", ErrNoThumbnail } raw := strings.Split(ggp.Sections[0].Cards[0].Element.Image.Base64Image, "base64,") if len(raw) < 2 { - return "", errors.New("cant decode ggp thumbnail") + return "", ErrNoThumbnail } return raw[1], nil diff --git a/services/webdav/pkg/preprocessor/preprocessor_test.go b/services/webdav/pkg/preprocessor/preprocessor_test.go index 08cffabb77..d2aaf151c9 100644 --- a/services/webdav/pkg/preprocessor/preprocessor_test.go +++ b/services/webdav/pkg/preprocessor/preprocessor_test.go @@ -3,15 +3,17 @@ package preprocessor import ( "archive/zip" "bytes" + "encoding/base64" "encoding/binary" "io" "os" + "strings" "testing" "golang.org/x/image/font" "golang.org/x/image/font/opentype" - . "github.com/onsi/ginkgo" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -77,6 +79,19 @@ var _ = Describe("preprocessor", func() { Expect(img).To(BeNil()) }) + It("reports a ggs without a thumbnail as having none", func() { + var buf bytes.Buffer + w := zip.NewWriter(&buf) + _, err := w.Create("geogebra.xml") + Expect(err).ToNot(HaveOccurred()) + Expect(w.Close()).To(Succeed()) + + decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: defaultMaxExtractedSize} + img, err := decoder.Convert(bytes.NewReader(buf.Bytes())) + Expect(err).To(MatchError(ErrNoThumbnail)) + Expect(img).To(BeNil()) + }) + It("refuses an entry that expands past the limit", func() { decoder := GgsDecoder{thumbnailpath: ggsThumbnailPath, maxSize: 1 << 20} @@ -109,7 +124,7 @@ var _ = Describe("preprocessor", func() { Expect(img.ContentType).To(HavePrefix("image/")) Expect(img.Data).ToNot(BeEmpty()) }) - It("should decode an audio", func() { + It("reports an audio without cover art as having none", func() { fileContent, err := os.ReadFile("test_assets/empty_no_image.mp3") if err != nil { panic(err) @@ -117,13 +132,46 @@ var _ = Describe("preprocessor", func() { fileReader = bytes.NewReader(fileContent) decoder := AudioDecoder{} img, err := decoder.Convert(fileReader) - Expect(err).To(HaveOccurred()) + Expect(err).To(MatchError(ErrNoThumbnail)) Expect(img).To(BeNil()) }) It("should return an error if the audio is invalid", func() { decoder := AudioDecoder{} img, err := decoder.Convert(bytes.NewReader([]byte("not an audio"))) Expect(err).To(HaveOccurred()) + Expect(err).ToNot(MatchError(ErrNoThumbnail)) + Expect(img).To(BeNil()) + }) + }) + + Describe("GgpDecoder", func() { + It("hands on the embedded thumbnail", func() { + data, err := os.ReadFile("test_assets/noise.png") + Expect(err).ToNot(HaveOccurred()) + ggp := `{"sections":[{"cards":[{"element":{"image":{"base64Image":"data:image/png;base64,` + base64.StdEncoding.EncodeToString(data) + `"}}}]}]}` + + img, err := GgpDecoder{}.Convert(strings.NewReader(ggp)) + Expect(err).ToNot(HaveOccurred()) + Expect(img.ContentType).To(Equal("image/png")) + Expect(img.Data).To(Equal(data)) + }) + + DescribeTable("reports a ggp without a thumbnail as having none", + func(ggp string) { + img, err := GgpDecoder{}.Convert(strings.NewReader(ggp)) + Expect(err).To(MatchError(ErrNoThumbnail)) + Expect(img).To(BeNil()) + }, + Entry("no sections", `{}`), + Entry("no cards", `{"sections":[{"cards":[]}]}`), + Entry("no base64 image", `{"sections":[{"cards":[{"element":{"image":{"base64Image":""}}}]}]}`), + Entry("not an image", `{"sections":[{"cards":[{"element":{"image":{"base64Image":"data:text/plain;base64,aGVsbG8="}}}]}]}`), + ) + + It("should return an error if the ggp is invalid", func() { + img, err := GgpDecoder{}.Convert(strings.NewReader("not a ggp")) + Expect(err).To(HaveOccurred()) + Expect(err).ToNot(MatchError(ErrNoThumbnail)) Expect(img).To(BeNil()) }) }) diff --git a/services/webdav/pkg/preprocessor/tika_test.go b/services/webdav/pkg/preprocessor/tika_test.go index fee3aaa6e4..3636ff4595 100644 --- a/services/webdav/pkg/preprocessor/tika_test.go +++ b/services/webdav/pkg/preprocessor/tika_test.go @@ -9,7 +9,7 @@ import ( "net/http" "net/http/httptest" - . "github.com/onsi/ginkgo" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/types" From d27aaa403f8e5db2203e983321065b839cb4f434 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 6 Nov 2026 12:13:35 +0100 Subject: [PATCH 16/19] docs(webdav): split the thumbnail README by topic, with setups as a table --- services/webdav/README.md | 94 ++++++++++++++++++++++++---- services/webdav/pkg/config/config.go | 4 +- 2 files changed, 83 insertions(+), 15 deletions(-) diff --git a/services/webdav/README.md b/services/webdav/README.md index 31391931e7..9905cc7f85 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -10,22 +10,55 @@ Currently, the webdav service handles request for two functionalities, which are The webdav service provides various `GET` endpoints to get the thumbnails of a file in authenticated and unauthenticated contexts. It also provides thumbnails for spaces on different endpoints. -When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Which types go there is a list, and the default is the formats a Tika release serves a thumbnail for: documents, ebooks, office and iWork files, audio cover art and the camera raws. `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) replaces that list, `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES` adds to it, a single `*` in either sends every type that nothing else claims, and an empty list sends nothing at all, which leaves a Tika server shared with the search service to the search service alone. An entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file: a raw read as a tiff is parsed as a tiff, its maker notes stay unread, and the embedded preview a thumbnail would be made of is never found. The formats in the default list are detected down to the leaf type, so none of them needs the hint, and it is there for the next format whose detection stops one level short. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. Who gets a file is decided in one order, first match wins, and every type has exactly one taker: +#### Who Makes a Thumbnail -1. a type the Tika list names goes to Tika, an image too, which is why the camera raws are named there: reva types them as images and no generator reads them -2. text, audio and GeoGebra go to the built-in extractors -3. an image goes to the generator as it is; whether it can read it is the generator's answer, an imagor with ImageMagick reads heic where the built-in one does not -4. anything else goes to Tika when the Tika list has `*` -5. and otherwise to the generator as it is +Three parties can turn a file into a thumbnail: -So `*` never sends an image: images belong to the generator, and sending one to Tika would only move the file. An image type that only Tika can read has to be named in the Tika list. Announcing a type in `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` and sending it to Tika are separate decisions: the announcement is what `oc:has-preview` reports, the Tika list says who makes the image. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well, and an empty list sends nothing at all, which leaves the Tika server to the search service alone. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black. +- the **generator** (imagor, or the thumbnails service in its place) scales images +- the **built-in converters** in the webdav service render plain text and extract audio cover art and GeoGebra thumbnails. The audio and GeoGebra extractors are deprecated in favour of Tika. +- an **Apache Tika server**, when configured, extracts a preview image from documents, ebooks, office files, audio, camera raws and more -Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again. +A thumbnail is only attempted for a type that is announced (`OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` plus the built-in list) or that Tika takes (named in the Tika list, or any type when the list contains `*`). Every other type answers `404` without the file being read. For the types that pass, the first rule that applies wins: -#### Tika Before 4.2.0 +1. a type the Tika list names goes to Tika, even an image (that is how camera raws get a preview: reva types them as images, and no generator reads them) +2. text, audio and GeoGebra go to the built-in converters +3. an image goes to the generator as it is +4. anything else goes to Tika if the Tika list contains `*` +5. what is left is an announced type, and it goes to the generator as it is, which answers whether it can read it -`TIKA_PRESETS` is read by Tika 4.2.0 and newer. A 4.1.x server serves the same -route when its config file activates the preset: +So `*` never sends an image to Tika. An image type that only Tika can read has to be named in the Tika list. + +#### Typical Setups + +| File | No Tika | Tika, default list | Default list plus `*` | List is only `*` | Empty list | +| --------------------- | ---------------- | ------------------ | --------------------- | ------------------------ | ---------------- | +| `photo.jpg` | generator | generator | generator | generator | generator | +| `photo.nef` (raw) | no preview | Tika | Tika | generator, 404 | no preview | +| `report.pdf`, `.docx` | no preview | Tika | Tika | Tika | no preview | +| `song.mp3` | built-in | Tika | Tika | built-in | built-in | +| `board.ggs` | built-in | Tika | Tika | built-in | built-in | +| `notes.txt` | built-in | built-in | built-in | built-in | built-in | +| `archive.zip` | no preview | no preview | Tika | Tika | no preview | + +- **Default list plus `*`**: `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES=*` +- **List is only `*`**: `OC_TIKA_THUMBNAIL_MIME_TYPES=*`. This replaces the default list, so the raws are no longer named and fall to the generator. +- **Empty list**: `OC_TIKA_THUMBNAIL_MIME_TYPES=""`. This keeps a Tika server that is shared with the search service for search alone. +- "no preview" means no attempt is made, and the request answers `404`. + +#### Tika and Thumbnails + +Set `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) to an Apache Tika server 4.2.0 or newer, started with `TIKA_PRESETS=thumbnail`. The webdav service calls `PUT /unpack/preset/thumbnail`, which only exists with that preset active. + +The Tika list starts from a default list: the formats a Tika release serves a thumbnail for, which are documents, ebooks, office and iWork files, GeoGebra, audio cover art and camera raws. It is configured with these variables: + +- `OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES` adds to the default list. This is the usual way to send more to Tika, including `*` for every type that no other rule claims. +- `OC_TIKA_THUMBNAIL_MIME_TYPES` replaces the default list. Use it to remove types from the default list, or set it empty to send nothing. Whatever it holds is the whole list, so a value of `*` alone drops the camera raws (see the table above). + +An entry can map a type to the name Tika uses for it, for example `image/x-nikon-nef:image/x-raw-nikon`. That name decides which Tika parser reads the file. A raw photo that Tika only detects as a plain tiff is parsed as a tiff, and its embedded preview is never found. Every format in the default list is detected correctly without a mapping. The mapping is meant for the next format whose detection stops one level short. + +##### Tika Before 4.2.0 + +`TIKA_PRESETS` is read by Tika 4.2.0 and newer. A 4.1.x server serves the same route when its config file activates the preset: ```json { @@ -34,8 +67,43 @@ route when its config file activates the preset: } ``` -It is passed with `-c /tika-config.json`, and the `server` block has to be in -there because the file replaces what the command line would say. +It is passed with `-c /tika-config.json`. The `server` block has to be in the file, because the file replaces what the command line would set. + +#### Announced Types and Output Types + +Announcing a type and sending it to Tika are separate settings: + +- `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` decides what `oc:has-preview` reports in a listing. +- The Tika list decides who makes the image. + +A type that Tika takes is attempted even when it is not announced. A direct request can therefore get a preview that a listing reports as absent. + +The thumbnail is written in the type that the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever Tika returns. The answer is the same before and after a cache hit. A Windows binary maps to `image/png` by default, because the icon Tika reads from it has transparency that a JPEG would flatten onto black. + +#### Thumbnail Cache + +The webdav service caches the thumbnails it generates. Choose a backend with `WEBDAV_THUMBNAILS_CACHE_BACKEND`: + +| Backend | Use case | +| ---------------- | -------------------------------------------------------------------------- | +| `file` (default) | single instance, entries under `$OC_BASE_DATA_PATH/thumbnails/cache`, change with `WEBDAV_THUMBNAILS_CACHE_DIR` | +| `s3` | several instances behind a load balancer that share one cache | +| `memory` | bounded, drops its oldest entries first | +| `none` | turns caching off on purpose | + +`s3` needs a bucket, a region and credentials. A service other than AWS also needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT`, and it is always addressed over https. While previews are enabled, an unknown backend or an incomplete `s3` configuration fails at startup rather than running without a cache. + +##### What Is Cached + +- every generated thumbnail, one entry per size +- once per file, the image an extractor (Tika or a built-in converter) got from it, so a second size does not extract again +- the fact that a file holds no image at all, so the extractor is asked only once + +A failed extraction (Tika unreachable, preset not active, a broken file) is not cached and is retried on the next request. + +##### Expiry + +Entries never expire. A changed file gets new entries, because the key contains the file's checksum. An extractor that learns a new format, however, does not revisit files it has already answered for. After such an upgrade (a new Apache Tika release, for example), empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) so those files are asked again. #### Thumbnail Query String Parameters diff --git a/services/webdav/pkg/config/config.go b/services/webdav/pkg/config/config.go index bfdaea2c16..fefdba5516 100644 --- a/services/webdav/pkg/config/config.go +++ b/services/webdav/pkg/config/config.go @@ -29,8 +29,8 @@ type Config struct { Thumbnails Thumbnails `yaml:"thumbnails"` TikaURL string `yaml:"tika_url" env:"OC_TIKA_URL;WEBDAV_TIKA_URL" desc:"URL of an Apache Tika server. When set, thumbnails are generated for documents, raw photos, audio cover art and other formats Tika can extract a preview from. Needs Tika 4.2.0 or newer, started with TIKA_PRESETS=thumbnail. A 4.1.x server works as well, with the preset activated in its config file instead." introductionVersion:"%%NEXT%%"` - TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail, which replaces the built-in list of the formats a Tika release serves one for. A named type goes to Tika before anything else, an image too: the camera raws are in that list because reva types them as images and an image the list does not name goes to the generator. A single '*' sends every other type that is neither an image nor has a built-in converter, so it never sends an image, and an empty list sends nothing at all, which leaves a Tika shared with the search service to the search service alone. An entry can map a type to the one Tika knows the format by, e.g. image/x-nikon-nef:image/x-raw-nikon. Tika takes a declared type only when it refines what it detected itself, so an entry pins the leaf type its detector left at the parent, a raw photo it only read as a plain tiff. The type decides which parser reads the file, so a raw read as a tiff loses its maker notes and with them the embedded preview; the formats shipped here are detected down to the leaf type, so no entry is needed for them." introductionVersion:"%%NEXT%%"` - AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail, on top of the built-in list or of whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. An entry carries a type hint the same way. An image type that only Tika can read has to be named here or there, '*' never sends an image." introductionVersion:"%%NEXT%%"` + TikaThumbnailMimeTypes []string `yaml:"tika_thumbnail_mime_types" env:"OC_TIKA_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_THUMBNAIL_MIME_TYPES" desc:"The mime types sent to Tika for their thumbnail. This replaces the built-in list of the formats a Tika release serves one for. Use it to remove types from that list, or set it empty to send nothing, which leaves a Tika server shared with the search service to the search service alone. To send more types, use OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES instead. Whatever this setting holds is the whole list, so a '*' alone drops the camera raws: reva types them as images, and only a named entry sends an image to Tika. A named type goes to Tika before anything else. An entry can map a type to the name Tika uses for the format, e.g. image/x-nikon-nef:image/x-raw-nikon. That name decides which parser reads the file, so a raw that Tika only detects as a plain tiff loses its embedded preview. The formats in the built-in list need no mapping." introductionVersion:"%%NEXT%%"` + AdditionalTikaThumbnailMimeTypes []string `yaml:"additional_tika_thumbnail_mime_types" env:"OC_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES;WEBDAV_TIKA_ADDITIONAL_THUMBNAIL_MIME_TYPES" desc:"Additional mime types sent to Tika for their thumbnail. They are added to the built-in list, or to whatever OC_TIKA_THUMBNAIL_MIME_TYPES names instead. This is the usual way to send more types to Tika. A single '*' sends every type that is neither an image nor has a built-in converter, so it never sends an image. An image type that only Tika can read has to be named. An entry can carry a type mapping the same way as in OC_TIKA_THUMBNAIL_MIME_TYPES." introductionVersion:"%%NEXT%%"` Context context.Context `yaml:"-"` } From 081a0a71ec2d8391883ec28b224ae3413bee2565 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 6 Nov 2026 12:20:46 +0100 Subject: [PATCH 17/19] fix(webdav): hash the source cache key like the thumbnail key --- .../webdav/pkg/thumbnail/workflow/workflow.go | 39 +++++++------------ .../pkg/thumbnail/workflow/workflow_test.go | 25 ++++++++++-- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 568fd46105..d3f73d4a70 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -123,34 +123,23 @@ func fileIsProcessing(info *providerv1beta1.ResourceInfo) bool { return utils.ReadPlainFromOpaque(info.GetOpaque(), "status") == "processing" } -// thumbnailStorageKey builds the cache key: hash[:2]/hash[2:4]/hash[4:]/wxh-.format. -// The segment (fit-in, fill, stretch, ...) distinguishes requests that -// share a size but produce different images, so they never share a cache entry. -// The key carries the snapped box, not the requested size, so every request that -// rounds to the same box shares one entry. Caches regenerate when the configured -// resolutions or operations change. -// -// The checksum is hashed rather than used as it comes: it is not this service's -// to trust, an OCM share takes it from a remote PROPFIND, and it ends up as a -// path on disk and as an object key. The source type is hashed with it, because -// the same bytes under two types are not the same thumbnail: the type picks the -// extractor, and what it finds depends on it. +// thumbnailStorageKey is /wxh-.format, with the snapped box as size. func thumbnailStorageKey(checksum, mimeType string, w, h int, format, operation string) string { + return storageKeyPrefix(checksum, mimeType) + "/" + fmt.Sprintf("%dx%d-%s.%s", w, h, operation, format) +} + +// sourceStorageKey holds the extracted image for all sizes; empty means the file has none. +func sourceStorageKey(checksum, mimeType string) string { + return storageKeyPrefix(checksum, mimeType) + "/source" +} + +// storageKeyPrefix hashes the checksum because it is untrusted (OCM takes it from a +// remote PROPFIND) and becomes a path; the type is included because it picks the extractor. +func storageKeyPrefix(checksum, mimeType string) string { sum := sha256.Sum256([]byte(checksum + "\x00" + mimeType)) hash := hex.EncodeToString(sum[:]) - return hash[:2] + "/" + hash[2:4] + "/" + hash[4:] + "/" + fmt.Sprintf("%dx%d-%s.%s", w, h, operation, format) -} - -// sourceStorageKey is where the image an extractor made of a file is -// remembered. What an extractor finds does not depend on the size that was -// asked for, so this one entry answers every request for the file, and an -// empty entry says the file carries no image at all. -func sourceStorageKey(checksum string) string { - if len(checksum) >= 6 { - return checksum[:2] + "/" + checksum[2:4] + "/" + checksum[4:] + "/source" - } - return checksum + "/source" + return hash[:2] + "/" + hash[2:4] + "/" + hash[4:] } // ThumbnailWorkflow owns the complete thumbnail generation pipeline: @@ -564,7 +553,7 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta // what the extraction found is remembered per file, so a second size does // not send the file to Tika again, and a file that carries nothing is only // asked once. The answer is read before the file is downloaded at all. - sourceKey := sourceStorageKey(checksum) + sourceKey := sourceStorageKey(checksum, mimeType) if converter != nil && w.cache != nil { if cached, err := w.cache.Get(sourceKey); err == nil { if len(cached) == 0 { diff --git a/services/webdav/pkg/thumbnail/workflow/workflow_test.go b/services/webdav/pkg/thumbnail/workflow/workflow_test.go index 94d2a72aea..b7ed971f3f 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow_test.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow_test.go @@ -10,6 +10,7 @@ import ( "net/http" "net/http/httptest" "os" + "path" "path/filepath" "strings" @@ -845,7 +846,7 @@ var _ = Describe("ThumbnailWorkflow", func() { _, err = wf2.Execute(context.Background(), tr, testToken, logger) Expect(err).ToNot(HaveOccurred()) - cached, err := testCache.Get("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source") + cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg")) Expect(err).ToNot(HaveOccurred()) Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size") }) @@ -853,7 +854,7 @@ var _ = Describe("ThumbnailWorkflow", func() { It("sends the kept source instead of extracting a second time", func() { pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png")) Expect(err).ToNot(HaveOccurred()) - Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", pngBytes)).To(Succeed()) + Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg"), pngBytes)).To(Succeed()) //the file itself is not an mp3: extracting it would fail, so what //reaches the generator can only come from the cache @@ -872,7 +873,7 @@ var _ = Describe("ThumbnailWorkflow", func() { }) It("asks once for a file that carries nothing, whatever size follows", func() { - Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", nil)).To(Succeed()) + Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg"), nil)).To(Succeed()) wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3")) @@ -1731,3 +1732,21 @@ var _ = Describe("postToGenerator", func() { Expect(partDisposition).To(Equal(`form-data; name="image"; filename="we\"ird.png"`)) }) }) + +var _ = Describe("storage keys", func() { + It("keeps a checksum from leaving the cache directory", func() { + key := sourceStorageKey("../../../../../tmp/x", "audio/mpeg") + Expect(key).To(MatchRegexp(`^[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{60}/source$`)) + }) + + It("gives the same bytes under two types two source entries", func() { + Expect(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "application/pdf")). + ToNot(Equal(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "text/plain"))) + }) + + It("files a thumbnail and its source under one prefix", func() { + source := sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef") + thumb := thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", 64, 64, "jpg", "fill") + Expect(path.Dir(thumb)).To(Equal(path.Dir(source))) + }) +}) From 253b2d4d5202d2e722db13ce219566b1e6a9e9aa Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 6 Nov 2026 12:26:37 +0100 Subject: [PATCH 18/19] fix(webdav): key the source cache by extractor, keep no empty entry per size --- .../webdav/pkg/preprocessor/preprocessor.go | 10 +++++ services/webdav/pkg/preprocessor/tika.go | 2 + .../webdav/pkg/thumbnail/workflow/workflow.go | 18 ++------- .../pkg/thumbnail/workflow/workflow_test.go | 38 +++++++++++++++---- 4 files changed, 46 insertions(+), 22 deletions(-) diff --git a/services/webdav/pkg/preprocessor/preprocessor.go b/services/webdav/pkg/preprocessor/preprocessor.go index 607ead90e7..89d1db0852 100644 --- a/services/webdav/pkg/preprocessor/preprocessor.go +++ b/services/webdav/pkg/preprocessor/preprocessor.go @@ -27,6 +27,8 @@ import ( // FileConverter is the interface for the file converter type FileConverter interface { Convert(r io.Reader) (*Image, error) + // Name tells cached results of different extractors apart. + Name() string } // Image is what a converter hands on: the bytes and the type they are in. @@ -47,6 +49,8 @@ type GgsDecoder struct { maxSize uint64 } +func (GgsDecoder) Name() string { return "oc-ggs" } + // Convert reads the ggs file and returns the thumbnail image. // // TODO: this parses user-provided bytes in-process (archive/zip streams the @@ -94,6 +98,8 @@ func (g GgsDecoder) Convert(r io.Reader) (*Image, error) { // Deprecated: Tika provides the cover art; kept for setups without Tika. type AudioDecoder struct{} +func (AudioDecoder) Name() string { return "oc-audio" } + // Convert reads the audio file and extracts the thumbnail image from the id3 tag. // // TODO: this parses user-provided bytes in-process (dhowden/tag reads the audio @@ -123,6 +129,8 @@ type TxtToImageConverter struct { fontLoader *FontLoader } +func (TxtToImageConverter) Name() string { return "oc-text" } + // Convert reads the text file and renders it into a thumbnail image func (t TxtToImageConverter) Convert(r io.Reader) (*Image, error) { img := image.NewRGBA(image.Rect(0, 0, 640, 480)) @@ -231,6 +239,8 @@ type GGPStruct struct { // Deprecated: see GgsDecoder. type GgpDecoder struct{} +func (GgpDecoder) Name() string { return "oc-ggp" } + // Convert reads the ggp file and returns the first thumbnail image. // // TODO: this parses user-provided bytes in-process (JSON/base64 extraction of diff --git a/services/webdav/pkg/preprocessor/tika.go b/services/webdav/pkg/preprocessor/tika.go index 56b2b813d2..1ef71b79fb 100644 --- a/services/webdav/pkg/preprocessor/tika.go +++ b/services/webdav/pkg/preprocessor/tika.go @@ -25,6 +25,8 @@ type TikaThumbnail struct { contentType string } +func (TikaThumbnail) Name() string { return "tika" } + // Convert hands the thumbnail on undecoded: the generator reads formats webdav // cannot, an .ico icon group out of a PE binary for one. func (t TikaThumbnail) Convert(r io.Reader) (*Image, error) { diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index d3f73d4a70..437a7b20d7 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -129,8 +129,8 @@ func thumbnailStorageKey(checksum, mimeType string, w, h int, format, operation } // sourceStorageKey holds the extracted image for all sizes; empty means the file has none. -func sourceStorageKey(checksum, mimeType string) string { - return storageKeyPrefix(checksum, mimeType) + "/source" +func sourceStorageKey(checksum, mimeType, extractor string) string { + return storageKeyPrefix(checksum, mimeType) + "/source-" + extractor } // storageKeyPrefix hashes the checksum because it is untrusted (OCM takes it from a @@ -464,11 +464,6 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R cached, err := w.cache.Get(cacheKey) switch { case err == nil: - // an empty entry is a file we know carries no thumbnail - if len(cached) == 0 { - return Thumbnail{}, ErrNoThumbnail - } - return Thumbnail{Data: cached, ContentType: outputType}, nil case !errors.Is(err, cache.ErrCacheMiss): // a miss is the normal answer; anything else is the cache itself @@ -483,13 +478,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, checksum, logger) if err != nil { if errors.Is(err, ErrNoThumbnail) { - // a file that carries no thumbnail is an answer, not a failure, and - // the empty entry keeps the next request from asking again logger.Debug().Err(err).Msg("no source image for thumbnail") - if w.cache != nil { - _ = w.cache.Put(cacheKey, nil) - } - return Thumbnail{}, err } @@ -553,8 +542,9 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta // what the extraction found is remembered per file, so a second size does // not send the file to Tika again, and a file that carries nothing is only // asked once. The answer is read before the file is downloaded at all. - sourceKey := sourceStorageKey(checksum, mimeType) + var sourceKey string if converter != nil && w.cache != nil { + sourceKey = sourceStorageKey(checksum, mimeType, converter.Name()) if cached, err := w.cache.Get(sourceKey); err == nil { if len(cached) == 0 { return nil, "", nil, ErrNoThumbnail diff --git a/services/webdav/pkg/thumbnail/workflow/workflow_test.go b/services/webdav/pkg/thumbnail/workflow/workflow_test.go index b7ed971f3f..4f96aff241 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow_test.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow_test.go @@ -846,7 +846,7 @@ var _ = Describe("ThumbnailWorkflow", func() { _, err = wf2.Execute(context.Background(), tr, testToken, logger) Expect(err).ToNot(HaveOccurred()) - cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg")) + cached, err := testCache.Get(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio")) Expect(err).ToNot(HaveOccurred()) Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size") }) @@ -854,7 +854,7 @@ var _ = Describe("ThumbnailWorkflow", func() { It("sends the kept source instead of extracting a second time", func() { pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png")) Expect(err).ToNot(HaveOccurred()) - Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg"), pngBytes)).To(Succeed()) + Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), pngBytes)).To(Succeed()) //the file itself is not an mp3: extracting it would fail, so what //reaches the generator can only come from the cache @@ -873,7 +873,7 @@ var _ = Describe("ThumbnailWorkflow", func() { }) It("asks once for a file that carries nothing, whatever size follows", func() { - Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg"), nil)).To(Succeed()) + Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), nil)).To(Succeed()) wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3")) @@ -887,6 +887,28 @@ var _ = Describe("ThumbnailWorkflow", func() { _, err := wf2.Execute(context.Background(), tr, testToken, logger) Expect(err).To(MatchError(ErrNoThumbnail)) Expect(captured.data).To(BeEmpty(), "the generator is not asked at all") + + _, err = testCache.Get(thumbnailStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", 256, 256, "jpg", "fill")) + Expect(err).To(MatchError(cache.ErrCacheMiss), "only the source entry says there is nothing") + }) + + It("does not take another extractor's empty answer", func() { + Expect(testCache.Put(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "tika"), nil)).To(Succeed()) + + mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3")) + Expect(err).ToNot(HaveOccurred()) + wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes) + + tr := &requests.ThumbnailRequest{ + Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"), + Filename: "song.mp3", + Width: 64, + Height: 64, + } + + _, err = wf2.Execute(context.Background(), tr, testToken, logger) + Expect(err).ToNot(HaveOccurred()) + Expect(captured.data).ToNot(BeEmpty()) }) It("extracts the embedded thumbnail from geogebra slides", func() { @@ -1735,17 +1757,17 @@ var _ = Describe("postToGenerator", func() { var _ = Describe("storage keys", func() { It("keeps a checksum from leaving the cache directory", func() { - key := sourceStorageKey("../../../../../tmp/x", "audio/mpeg") - Expect(key).To(MatchRegexp(`^[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{60}/source$`)) + key := sourceStorageKey("../../../../../tmp/x", "audio/mpeg", "tika") + Expect(key).To(MatchRegexp(`^[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{60}/source-tika$`)) }) It("gives the same bytes under two types two source entries", func() { - Expect(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "application/pdf")). - ToNot(Equal(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "text/plain"))) + Expect(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "application/pdf", "tika")). + ToNot(Equal(sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "text/plain", "oc-text"))) }) It("files a thumbnail and its source under one prefix", func() { - source := sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef") + source := sourceStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", "tika") thumb := thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", 64, 64, "jpg", "fill") Expect(path.Dir(thumb)).To(Equal(path.Dir(source))) }) From 4443a8f9fcad74cc66263fd60ec32b86d94f7cb4 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 6 Nov 2026 12:30:02 +0100 Subject: [PATCH 19/19] fix(webdav): bound a kept source only by the cache's own limit --- services/webdav/pkg/thumbnail/workflow/workflow.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/webdav/pkg/thumbnail/workflow/workflow.go b/services/webdav/pkg/thumbnail/workflow/workflow.go index 437a7b20d7..3189797059 100644 --- a/services/webdav/pkg/thumbnail/workflow/workflow.go +++ b/services/webdav/pkg/thumbnail/workflow/workflow.go @@ -600,9 +600,6 @@ func (w *ThumbnailWorkflow) rememberSource(key string, data []byte) { if w.cache == nil || len(data) > maxCachedSourceBytes { return } - if w.maxInputSize > 0 && uint64(len(data)) > w.maxInputSize { - return - } _ = w.cache.Put(key, data) }