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