mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-11-27 10:34:42 -05:00
208 lines
6.9 KiB
Go
208 lines
6.9 KiB
Go
package content
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
|
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
|
"github.com/google/go-tika/tika"
|
|
"github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool"
|
|
|
|
"github.com/opencloud-eu/opencloud/pkg/log"
|
|
"github.com/opencloud-eu/opencloud/services/search/pkg/config"
|
|
)
|
|
|
|
// ErrUnparsable marks a file tika answered for but could not parse, unlike an
|
|
// unreachable tika it fails the same way on the next attempt more often than not
|
|
var ErrUnparsable = errors.New("tika failed to parse")
|
|
|
|
// tika answers its version without parsing anything, even while busy with a file
|
|
var probeTimeout = 5 * time.Second
|
|
|
|
// Tika is used to extract content from a resource,
|
|
// it uses apache tika to retrieve all the data.
|
|
type Tika struct {
|
|
*Basic
|
|
Retriever
|
|
tika *tika.Client
|
|
tikaURL string
|
|
ContentExtractionSizeLimit uint64
|
|
CleanStopWords bool
|
|
Timeout time.Duration
|
|
}
|
|
|
|
// NewTikaExtractor creates a new Tika instance.
|
|
func NewTikaExtractor(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], logger log.Logger, cfg *config.Config) (*Tika, error) {
|
|
basic, err := NewBasicExtractor(logger)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
tk := tika.NewClient(nil, cfg.Extractor.Tika.TikaURL)
|
|
tkv, err := tk.Version(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
logger.Info().Msgf("Tika version: %s", tkv)
|
|
|
|
return &Tika{
|
|
Basic: basic,
|
|
Retriever: newCS3Retriever(gatewaySelector, logger, cfg.Extractor.CS3AllowInsecure),
|
|
tika: tika.NewClient(nil, cfg.Extractor.Tika.TikaURL),
|
|
tikaURL: cfg.Extractor.Tika.TikaURL,
|
|
ContentExtractionSizeLimit: cfg.ContentExtractionSizeLimit,
|
|
CleanStopWords: cfg.Extractor.Tika.CleanStopWords,
|
|
Timeout: cfg.Extractor.Tika.Timeout,
|
|
}, nil
|
|
}
|
|
|
|
// Extract loads a resource from its underlying storage, passes it to tika and processes the result into a Document.
|
|
func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, error) {
|
|
doc, err := t.Basic.Extract(ctx, ri)
|
|
if err != nil {
|
|
return doc, err
|
|
}
|
|
|
|
if !t.Remote(ri) {
|
|
if ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > t.ContentExtractionSizeLimit {
|
|
t.logger.Info().Interface("ResourceID", ri.GetId()).Str("Name", ri.GetName()).Msg("file exceeds content extraction size limit. skipping.")
|
|
}
|
|
return doc, nil
|
|
}
|
|
|
|
// a tika that hangs instead of refusing connections would block the walk
|
|
attemptCtx := ctx
|
|
if t.Timeout > 0 {
|
|
var cancel context.CancelFunc
|
|
attemptCtx, cancel = context.WithTimeout(ctx, t.Timeout)
|
|
defer cancel()
|
|
}
|
|
|
|
data, err := t.Retrieve(attemptCtx, ri.GetId())
|
|
if err != nil {
|
|
return doc, t.attemptError(ctx, attemptCtx, ri, err)
|
|
}
|
|
defer data.Close()
|
|
|
|
metas, err := t.tika.MetaRecursive(attemptCtx, data)
|
|
if err != nil {
|
|
return doc, t.attemptError(ctx, attemptCtx, ri, unreachable(err))
|
|
}
|
|
// a file with content always yields metadata, none means tika failed on it
|
|
if len(metas) == 0 {
|
|
return doc, fmt.Errorf("%w %q: no metadata", ErrUnparsable, ri.GetName())
|
|
}
|
|
// tika answers a failed parse (ocr crash, broken pdf) with 200 and empty
|
|
// content, only this key tells it apart from a file without text
|
|
cause, err := getFirstValue(metas[0],
|
|
"tk:exception:container-exception", // tika 4
|
|
"X-TIKA:EXCEPTION:container_exception", // tika 3 legacy
|
|
)
|
|
if err == nil {
|
|
// the value is a java stack trace, its first line names the cause
|
|
cause, _, _ = strings.Cut(cause, "\n")
|
|
return doc, fmt.Errorf("%w %q: %s", ErrUnparsable, ri.GetName(), cause)
|
|
}
|
|
|
|
for _, meta := range metas {
|
|
title, err := getFirstValue(meta, "dc:title")
|
|
if err != nil {
|
|
title, err = getFirstValue(meta, "title")
|
|
}
|
|
if err == nil {
|
|
doc.Title = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Title, title))
|
|
}
|
|
|
|
if content, err := getFirstValue(meta,
|
|
"tk:content", // tika 4
|
|
"X-TIKA:content", // tika 3 legacy
|
|
); err == nil {
|
|
doc.Content = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Content, content))
|
|
}
|
|
}
|
|
|
|
// facets describe the file itself, not its embedded parts (cover art, clips)
|
|
m0 := metas[0]
|
|
doc.Location = t.getLocation(m0)
|
|
doc.Image = t.getImage(m0)
|
|
doc.Photo = t.getPhoto(m0)
|
|
doc.Audio = t.getAudio(m0)
|
|
doc.LivePhoto = t.getLivePhoto(m0)
|
|
doc.Video = t.getVideo(m0)
|
|
|
|
// a motion photo is the file's own xmp plus the video tika extracted from
|
|
// it; the xmp alone proves nothing, a share can strip the appended clip
|
|
if i := slices.IndexFunc(metas[1:], isVideo); i >= 0 {
|
|
doc.MotionPhoto = t.getMotionPhoto(m0, metas[i+1])
|
|
}
|
|
|
|
if langCode := t.detectLanguage(attemptCtx, doc.Content); langCode != "" && t.CleanStopWords {
|
|
doc.Content = CleanString(doc.Content, langCode)
|
|
}
|
|
|
|
return doc, nil
|
|
}
|
|
|
|
// Remote tells whether extracting ri goes to tika, only a file with content
|
|
// within the size limit does
|
|
func (t Tika) Remote(ri *provider.ResourceInfo) bool {
|
|
return ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > 0 && ri.GetSize() <= t.ContentExtractionSizeLimit
|
|
}
|
|
|
|
// Probe asks tika for its version, which tells a tika that is down or hangs
|
|
// from one busy with a hard file
|
|
func (t Tika) Probe(ctx context.Context) error {
|
|
ctx, cancel := context.WithTimeout(ctx, probeTimeout)
|
|
defer cancel()
|
|
_, err := t.tika.Version(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", ErrUnreachable, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// attemptError turns an attempt that ran out of time into a failure of the file:
|
|
// tika accepted the request, so a retry would most likely run as long again and
|
|
// stack more work on a tika that may still be parsing. Unless tika does not even
|
|
// answer its version, then it hangs and is unreachable.
|
|
func (t Tika) attemptError(ctx, attemptCtx context.Context, ri *provider.ResourceInfo, err error) error {
|
|
if ctx.Err() != nil || !errors.Is(attemptCtx.Err(), context.DeadlineExceeded) {
|
|
return err
|
|
}
|
|
err = fmt.Errorf("extracting %q took longer than %s: %w", ri.GetName(), t.Timeout, context.DeadlineExceeded)
|
|
probeErr := t.Probe(ctx)
|
|
if probeErr != nil {
|
|
return fmt.Errorf("%w, %w", probeErr, err)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// detectLanguage asks tika for the language of content. Tika 4 moved the
|
|
// endpoint from /language/string to /language, so try the new path first and
|
|
// fall back for an older tika.
|
|
func (t Tika) detectLanguage(ctx context.Context, content string) string {
|
|
for _, path := range []string{"/language", "/language/string"} {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPut, t.tikaURL+path, strings.NewReader(content))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
lang, err := io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if err == nil && res.StatusCode == http.StatusOK && len(lang) > 0 {
|
|
return string(lang)
|
|
}
|
|
}
|
|
return ""
|
|
}
|