mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
Merge pull request #3332 from opencloud-eu/feat/thumbnails-raw-embedded-preview
feat(webdav): extract thumbnails through Tika
This commit is contained in:
27 files changed
+1085
-125
No files matched your search
@@ -3395,6 +3395,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",
|
||||
|
||||
@@ -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"
|
||||
@@ -163,7 +163,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:
|
||||
|
||||
|
||||
@@ -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%%"`
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -10,7 +10,100 @@ 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.
|
||||
|
||||
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.
|
||||
#### Who Makes a Thumbnail
|
||||
|
||||
Three parties can turn a file into a thumbnail:
|
||||
|
||||
- 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
|
||||
|
||||
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:
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
{
|
||||
"server": { "port": 9998, "host": "0.0.0.0" },
|
||||
"presets": { "thumbnail": true }
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
@@ -76,7 +169,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.
|
||||
|
||||
|
||||
@@ -28,6 +28,10 @@ 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. 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:"-"`
|
||||
}
|
||||
|
||||
@@ -50,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"`
|
||||
|
||||
@@ -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,6 +45,8 @@ func DefaultConfig() *config.Config {
|
||||
WebdavNamespace: "/users/{{.Id.OpaqueId}}",
|
||||
RevaGateway: shared.DefaultRevaConfig().Address,
|
||||
|
||||
TikaThumbnailMimeTypes: thumbnail.DefaultTikaTypes,
|
||||
|
||||
Thumbnails: config.Thumbnails{
|
||||
GeneratorURL: "http://127.0.0.1:9186",
|
||||
GeneratorTimeout: "30s",
|
||||
|
||||
@@ -2,9 +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")
|
||||
)
|
||||
var ErrNoThumbnail = errors.New("preprocessor: the document has no thumbnail")
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
@@ -26,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.
|
||||
@@ -36,15 +39,18 @@ 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
|
||||
}
|
||||
|
||||
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
|
||||
@@ -84,12 +90,16 @@ 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
|
||||
// AudioDecoder is a converter for the audio file.
|
||||
//
|
||||
// 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
|
||||
@@ -107,12 +117,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
|
||||
@@ -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))
|
||||
@@ -226,9 +234,13 @@ 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{}
|
||||
|
||||
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
|
||||
@@ -254,7 +266,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
|
||||
@@ -262,12 +274,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
|
||||
@@ -355,13 +367,39 @@ type Options struct {
|
||||
FontMapFile string
|
||||
FontFace *opentype.FaceOptions
|
||||
MaxImageSize uint64
|
||||
Tika thumbnail.Tika
|
||||
Filename string
|
||||
}
|
||||
|
||||
// ForType returns the converter for the specified mimeType
|
||||
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, 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.
|
||||
//
|
||||
// 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 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 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.
|
||||
// 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 toTika(opts, mimeType)
|
||||
}
|
||||
|
||||
switch mimeType {
|
||||
case "text/plain":
|
||||
fontFace := opts.FontFace
|
||||
@@ -379,22 +417,23 @@ func ForType(mimeType string, opts Options) FileConverter {
|
||||
// try to use the default font
|
||||
fontLoader, _ = NewFontLoader("", fontFace)
|
||||
}
|
||||
return TxtToImageConverter{
|
||||
fontLoader: fontLoader,
|
||||
}
|
||||
|
||||
return TxtToImageConverter{fontLoader: fontLoader}
|
||||
case "application/vnd.geogebra.slides":
|
||||
return GgsDecoder{thumbnailpath: "_slide0/geogebra_thumbnail.png", maxSize: maxExtractedSize(opts)}
|
||||
case "application/vnd.geogebra.pinboard":
|
||||
return GgpDecoder{}
|
||||
case "audio/flac":
|
||||
fallthrough
|
||||
case "audio/mpeg":
|
||||
fallthrough
|
||||
case "audio/ogg":
|
||||
case "audio/flac", "audio/mpeg", "audio/ogg":
|
||||
return AudioDecoder{}
|
||||
default:
|
||||
// webdav decodes no image: a type without a converter is streamed to
|
||||
// the generator untouched, which answers whether it can read it.
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mimeType, "image/") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.Tika.TakesAll() {
|
||||
return toTika(opts, mimeType)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -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())
|
||||
})
|
||||
})
|
||||
@@ -165,7 +213,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,8 +229,8 @@ 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("hands an announced type without a converter to the generator, which says whether it reads it", func() {
|
||||
Expect(ForType("application/pdf", Options{})).To(BeNil())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
package preprocessor
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"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
|
||||
}
|
||||
|
||||
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) {
|
||||
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 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.
|
||||
// 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"
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPut, strings.TrimRight(tikaURL, "/")+"/unpack/preset/thumbnail", bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
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))
|
||||
}
|
||||
|
||||
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
|
||||
case http.StatusNotFound:
|
||||
// the route exists once the catalog preset is active
|
||||
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)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxTikaResponse))
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("tika unpack 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)
|
||||
}
|
||||
return thumbnailFromZip(zr)
|
||||
}
|
||||
|
||||
// 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 f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
img, err := readZipEntry(zr, f.Name)
|
||||
if err != nil || len(img) == 0 {
|
||||
continue
|
||||
}
|
||||
contentType := entryContentType(f.Name, img)
|
||||
if !strings.HasPrefix(contentType, "image/") {
|
||||
continue
|
||||
}
|
||||
return contentType, img, nil
|
||||
}
|
||||
return "", nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
return http.DetectContentType(data)
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package preprocessor
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/onsi/gomega/types"
|
||||
|
||||
"github.com/opencloud-eu/opencloud/services/webdav/pkg/thumbnail"
|
||||
)
|
||||
|
||||
// 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 {
|
||||
w, err := zw.Create(name)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = w.Write(data)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}
|
||||
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})
|
||||
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/preset/thumbnail" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
thumbnail(w, r)
|
||||
}))
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
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(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")))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img).ToNot(BeNil())
|
||||
Expect(requests).To(HaveLen(1))
|
||||
})
|
||||
|
||||
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")
|
||||
//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(),
|
||||
}))
|
||||
}
|
||||
|
||||
img, err := TikaThumbnail{tikaURL: server.URL, filename: "document.pdf"}.Convert(bytes.NewReader([]byte("pdf")))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img).ToNot(BeNil())
|
||||
Expect(img.ContentType).To(Equal("image/png"))
|
||||
Expect(img.Data).To(Equal(pngBytes()))
|
||||
})
|
||||
|
||||
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(presetZip(map[string][]byte{"thumbnail": pngBytes()}))
|
||||
}
|
||||
|
||||
img, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw")))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img).ToNot(BeNil(), "the bytes name the type when the entry does not")
|
||||
})
|
||||
|
||||
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 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) }
|
||||
|
||||
_, err := TikaThumbnail{tikaURL: server.URL}.Convert(bytes.NewReader([]byte("raw")))
|
||||
Expect(err).To(MatchError(ContainSubstring("500")))
|
||||
})
|
||||
|
||||
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")
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("ForType with a Tika server", func() {
|
||||
const tikaURL = "http://tika:9998"
|
||||
named := thumbnail.NewTika(tikaURL, thumbnail.DefaultTikaTypes, nil)
|
||||
everything := thumbnail.NewTika(tikaURL, []string{"*"}, nil)
|
||||
off := thumbnail.NewTika("", thumbnail.DefaultTikaTypes, nil)
|
||||
|
||||
tika := BeAssignableToTypeOf(TikaThumbnail{})
|
||||
generator := BeNil()
|
||||
|
||||
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},
|
||||
|
||||
{"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{})},
|
||||
|
||||
{"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() {
|
||||
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"))
|
||||
})
|
||||
})
|
||||
@@ -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, conf.AdditionalTikaThumbnailMimeTypes)),
|
||||
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)))
|
||||
|
||||
@@ -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"),
|
||||
)
|
||||
})
|
||||
+4
-17
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -6,11 +6,9 @@ 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, announced
|
||||
// without further configuration.
|
||||
var GeneratorImageTypes = []string{
|
||||
"image/png",
|
||||
"image/jpg",
|
||||
"image/jpeg",
|
||||
@@ -19,13 +17,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
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
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("Supports",
|
||||
func(types thumbnail.SourceTypes, mimeType string, want bool) {
|
||||
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("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),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
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",
|
||||
"audio/x-m4b",
|
||||
|
||||
"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.
|
||||
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. 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 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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
m, _, err := mime.ParseMediaType(mimeType)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, named := t.mimeTypes[m]
|
||||
|
||||
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
|
||||
// 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 {
|
||||
return ""
|
||||
}
|
||||
if theirs := t.mimeTypes[m]; theirs != "" {
|
||||
return theirs
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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("", 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) {
|
||||
Expect(tika.Supports(mimeType)).To(Equal(want))
|
||||
},
|
||||
Entry("nothing without a server", none, "application/pdf", false),
|
||||
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),
|
||||
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",
|
||||
func(tika thumbnail.Tika, mimeType, want string) {
|
||||
Expect(tika.ContentType(mimeType)).To(Equal(want))
|
||||
},
|
||||
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"),
|
||||
)
|
||||
})
|
||||
@@ -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",
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
|
||||
@@ -73,6 +73,10 @@ 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")
|
||||
|
||||
// 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")
|
||||
@@ -119,23 +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-<operation>.format.
|
||||
// The <operation> 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 <prefix>/wxh-<operation>.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, extractor string) string {
|
||||
return storageKeyPrefix(checksum, mimeType) + "/source-" + extractor
|
||||
}
|
||||
|
||||
// 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)
|
||||
return hash[:2] + "/" + hash[2:4] + "/" + hash[4:]
|
||||
}
|
||||
|
||||
// ThumbnailWorkflow owns the complete thumbnail generation pipeline:
|
||||
@@ -148,6 +152,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 +238,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 +325,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())
|
||||
}
|
||||
|
||||
@@ -422,15 +432,13 @@ 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 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)
|
||||
|
||||
// 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
|
||||
@@ -464,23 +472,28 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
logger.Debug().Err(err).Msg("no source image for thumbnail")
|
||||
return Thumbnail{}, err
|
||||
}
|
||||
|
||||
logger.Error().Err(err).Msg("could not obtain source image for thumbnail")
|
||||
|
||||
return Thumbnail{}, err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
// 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)
|
||||
|
||||
// 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.
|
||||
imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, logger)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("could not obtain source image for thumbnail")
|
||||
return Thumbnail{}, err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
thumbBytes, thumbType, err := w.postToGenerator(ctx, genURL, imgStream, tr.Filename, srcType)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("could not generate thumbnail")
|
||||
@@ -507,27 +520,50 @@ 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.
|
||||
func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename string, logger log.Logger) (io.Reader, string, func(), error) {
|
||||
// - 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)
|
||||
|
||||
converter := preprocessor.ForType(m, preprocessor.Options{FontMapFile: w.fontMapFile, MaxImageSize: w.maxInputSize})
|
||||
if converter == nil {
|
||||
body, err := w.fileDownloader.DownloadStream(ctx, ref, auth)
|
||||
if err != nil {
|
||||
return nil, "", nil, fmt.Errorf("download: %w", err)
|
||||
// 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,
|
||||
})
|
||||
|
||||
// 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.
|
||||
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
|
||||
}
|
||||
|
||||
//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
|
||||
}
|
||||
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)
|
||||
@@ -536,14 +572,57 @@ 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
|
||||
}
|
||||
_ = 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 {
|
||||
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
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -829,6 +830,87 @@ 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(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")
|
||||
})
|
||||
|
||||
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", "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
|
||||
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(sourceStorageKey("1f0c9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b", "audio/mpeg", "oc-audio"), 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")
|
||||
|
||||
_, 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() {
|
||||
ggsBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "ggs_test.ggs"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@@ -1672,3 +1754,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", "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", "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", "tika")
|
||||
thumb := thumbnailStorageKey("cb56752477cae6405f85b131872c60d21b967c6a", "image/x-nikon-nef", 64, 64, "jpg", "fill")
|
||||
Expect(path.Dir(thumb)).To(Equal(path.Dir(source)))
|
||||
})
|
||||
})
|
||||
+5
-1
@@ -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.
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user