forked from google/go-tika
/
tika.go
271 lines (238 loc) · 9.38 KB
/
tika.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tika
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strings"
"golang.org/x/net/context/ctxhttp"
)
// Client represents a connection to a Tika Server.
type Client struct {
// url is the URL of the Tika Server, including the port (if necessary), but
// not the trailing slash. For example, http://localhost:9998.
url string
// HTTPClient is the client that will be used to call the Tika Server. If no
// client is specified, a default client will be used. Since http.Clients are
// thread safe, the same client will be used for all requests by this Client.
httpClient *http.Client
}
// NewClient creates a new Client. If httpClient is nil, the http.DefaultClient will be
// used.
func NewClient(httpClient *http.Client, urlString string) *Client {
return &Client{httpClient: httpClient, url: urlString}
}
// A Parser represents a Tika Parser. To get a list of all Parsers, see Parsers().
type Parser struct {
Name string
Decorated bool
Composite bool
Children []Parser
SupportedTypes []string
}
// MIMEType represents a Tika MIME Type. To get a list of all MIME Types, see
// MIMETypes.
type MIMEType struct {
Alias []string
SuperType string
}
// A Detector represents a Tika Detector. Detectors are used to get the filetype
// of a file. To get a list of all Detectors, see Detectors().
type Detector struct {
Name string
Composite bool
Children []Detector
}
// Translator represents the Java package of a Tika Translator.
type Translator string
// Translators available by defult in Tika. You must configure all required
// authentication details in Tika Server (for example, an API key).
const (
Lingo24Translator Translator = "org.apache.tika.language.translate.Lingo24Translator"
GoogleTranslator Translator = "org.apache.tika.language.translate.GoogleTranslator"
MosesTranslator Translator = "org.apache.tika.language.translate.MosesTranslator"
JoshuaTranslator Translator = "org.apache.tika.language.translate.JoshuaTranslator"
MicrosoftTranslator Translator = "org.apache.tika.language.translate.MicrosoftTranslator"
YandexTranslator Translator = "org.apache.tika.language.translate.YandexTranslator"
)
// XTIKAContent is the metadata field of the content of a file after recursive
// parsing. See ParseRecursive and MetaRecursive.
const XTIKAContent = "X-TIKA:content"
// call makes the given request to c and returns the result as a []byte and
// error. call returns an error if the response code is not 200 StatusOK.
func (c *Client) call(ctx context.Context, input io.Reader, method, path string, header http.Header) ([]byte, error) {
if c.httpClient == nil {
c.httpClient = http.DefaultClient
}
req, err := http.NewRequest(method, c.url+path, input)
if err != nil {
return nil, err
}
req.Header = header
resp, err := ctxhttp.Do(ctx, c.httpClient, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("response code %v", resp.StatusCode)
}
return ioutil.ReadAll(resp.Body)
}
// callString makes the given request to c and returns the result as a string
// and error. callString returns an error if the response code is not 200 StatusOK.
func (c *Client) callString(ctx context.Context, input io.Reader, method, path string) (string, error) {
body, err := c.call(ctx, input, method, path, nil)
if err != nil {
return "", err
}
return string(body), nil
}
// Parse parses the given input, returning the body of the input and an error.
// If the error is not nil, the body is undefined.
func (c *Client) Parse(ctx context.Context, input io.Reader) (string, error) {
return c.callString(ctx, input, "PUT", "/tika")
}
// ParseRecursive parses the given input and all embedded documents, returning a
// list of the contents of the input with one element per document. See
// MetaRecursive for access to all metadata fields. If the error is not nil, the
// result is undefined.
func (c *Client) ParseRecursive(ctx context.Context, input io.Reader) ([]string, error) {
m, err := c.MetaRecursive(ctx, input)
if err != nil {
return nil, err
}
var r []string
for _, d := range m {
if content := d[XTIKAContent]; len(content) > 0 {
r = append(r, content[0])
}
}
return r, nil
}
// Meta parses the metadata from the given input, returning the metadata and an
// error. If the error is not nil, the metadata is undefined.
func (c *Client) Meta(ctx context.Context, input io.Reader) (string, error) {
return c.callString(ctx, input, "PUT", "/meta")
}
// MetaField parses the metadata from the given input and returns the given
// field. If the error is not nil, the result string is undefined.
func (c *Client) MetaField(ctx context.Context, input io.Reader, field string) (string, error) {
return c.callString(ctx, input, "PUT", fmt.Sprintf("/meta/%v", field))
}
// Detect gets the mimetype of the given input, returning the mimetype and an
// error. If the error is not nil, the mimetype is undefined.
func (c *Client) Detect(ctx context.Context, input io.Reader) (string, error) {
return c.callString(ctx, input, "PUT", "/detect/stream")
}
// Language detects the language of the given input, returning the two letter
// language code and an error. If the error is not nil, the language is
// undefined.
func (c *Client) Language(ctx context.Context, input io.Reader) (string, error) {
return c.callString(ctx, input, "PUT", "/language/stream")
}
// LanguageString detects the language of the given string, returning the two letter
// language code and an error. If the error is not nil, the language is
// undefined.
func (c *Client) LanguageString(ctx context.Context, input string) (string, error) {
r := strings.NewReader(input)
return c.callString(ctx, r, "PUT", "/language/string")
}
// MetaRecursive parses the given input and all embedded documents. The result
// is a list of maps from metadata key to value for each document. The content
// of each document is in the XTIKAContent field. See ParseRecursive to just get
// the content of each document. If the error is not nil, the result list is
// undefined.
func (c *Client) MetaRecursive(ctx context.Context, input io.Reader) ([]map[string][]string, error) {
body, err := c.call(ctx, input, "PUT", "/rmeta/text", nil)
if err != nil {
return nil, err
}
var m []map[string]interface{}
if err := json.Unmarshal(body, &m); err != nil {
return nil, err
}
var r []map[string][]string
for _, d := range m {
doc := make(map[string][]string)
r = append(r, doc)
for k, v := range d {
switch vt := v.(type) {
case string:
doc[k] = []string{vt}
case []interface{}:
for _, i := range vt {
s, ok := i.(string)
if !ok {
return nil, fmt.Errorf("field %q has value %v and type %T, expected a string or []string", k, v, vt)
}
doc[k] = append(doc[k], s)
}
default:
return nil, fmt.Errorf("field %q has value %v and type %v, expected a string or []string", k, v, reflect.TypeOf(v))
}
}
}
return r, nil
}
// Translate returns an error and the translated input from src language to
// dst language using t. If the error is not nil, the translation is undefined.
func (c *Client) Translate(ctx context.Context, input io.Reader, t Translator, src, dst string) (string, error) {
return c.callString(ctx, input, "POST", fmt.Sprintf("/translate/all/%s/%s/%s", t, src, dst))
}
// Version returns the default hello message from Tika server.
func (c *Client) Version(ctx context.Context) (string, error) {
return c.callString(ctx, nil, "GET", "/version")
}
var jsonHeader = http.Header{"Accept": []string{"application/json"}}
// callUnmarshal is like call, but unmarshals the JSON response into v.
func (c *Client) callUnmarshal(ctx context.Context, path string, v interface{}) error {
body, err := c.call(ctx, nil, "GET", path, jsonHeader)
if err != nil {
return err
}
return json.Unmarshal(body, v)
}
// Parsers returns the list of available parsers and an error. If the error is
// not nil, the list is undefined. To get all available parsers, iterate through
// the Children of every Parser.
func (c *Client) Parsers(ctx context.Context) (*Parser, error) {
p := new(Parser)
if err := c.callUnmarshal(ctx, "/parsers/details", p); err != nil {
return nil, err
}
return p, nil
}
// MIMETypes returns a map from MIME Type name to MIMEType, or properties about
// that specific MIMEType.
func (c *Client) MIMETypes(ctx context.Context) (map[string]MIMEType, error) {
mt := make(map[string]MIMEType)
if err := c.callUnmarshal(ctx, "/mime-types", &mt); err != nil {
return nil, err
}
return mt, nil
}
// Detectors returns the list of available Detectors for this server. To get all
// available detectors, iterate through the Children of every Detector.
func (c *Client) Detectors(ctx context.Context) (*Detector, error) {
d := new(Detector)
if err := c.callUnmarshal(ctx, "/detectors", d); err != nil {
return nil, err
}
return d, nil
}