Making default pdf extracting more robust (#17675)
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
97a7653373
Коммит
d320b50abb
@@ -5,6 +5,7 @@ package docextractor
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
@@ -25,7 +26,13 @@ func (pe *pdfExtractor) Match(filename string) bool {
|
|||||||
return supportedExtensions[extension]
|
return supportedExtensions[extension]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pe *pdfExtractor) Extract(filename string, r io.ReadSeeker) (string, error) {
|
func (pe *pdfExtractor) Extract(filename string, r io.ReadSeeker) (out string, outErr error) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
out = ""
|
||||||
|
outErr = errors.New("error extracting pdf text")
|
||||||
|
}
|
||||||
|
}()
|
||||||
f, err := ioutil.TempFile(os.TempDir(), "pdflib")
|
f, err := ioutil.TempFile(os.TempDir(), "pdflib")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("error creating temporary file: %v", err)
|
return "", fmt.Errorf("error creating temporary file: %v", err)
|
||||||
|
|||||||
36
services/docextractor/pdf_test.go
Обычный файл
36
services/docextractor/pdf_test.go
Обычный файл
@@ -0,0 +1,36 @@
|
|||||||
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||||
|
// See LICENSE.txt for license information.
|
||||||
|
|
||||||
|
package docextractor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mattermost/mattermost-server/v5/utils/testutils"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPdfEmptyFile(t *testing.T) {
|
||||||
|
extractor := pdfExtractor{}
|
||||||
|
_, err := extractor.Extract("test.pdf", bytes.NewReader([]byte{}))
|
||||||
|
require.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPdfFile(t *testing.T) {
|
||||||
|
extractor := pdfExtractor{}
|
||||||
|
contentText := "This is a simple document that contains some text."
|
||||||
|
content, err := testutils.ReadTestFile("sample-doc.pdf")
|
||||||
|
require.NoError(t, err)
|
||||||
|
extractedText, err := extractor.Extract("sample-doc.pdf", bytes.NewReader(content))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, contentText, extractedText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrongPdfFile(t *testing.T) {
|
||||||
|
extractor := pdfExtractor{}
|
||||||
|
content, err := testutils.ReadTestFile("sample-doc.docx")
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = extractor.Extract("sample-doc.pdf", bytes.NewReader(content))
|
||||||
|
require.Error(t, err)
|
||||||
|
}
|
||||||
Ссылка в новой задаче
Block a user