/
stardict.go
366 lines (313 loc) · 8.24 KB
/
stardict.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2021 Google LLC
//
// 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 stardict
import (
"compress/gzip"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/pebbe/dictzip"
"github.com/ianlewis/go-stardict/dict"
"github.com/ianlewis/go-stardict/idx"
"github.com/ianlewis/go-stardict/ifo"
)
const ifoMagic = "StarDict's dict ifo file"
// Stardict is a stardict dictionary.
type Stardict struct {
ifo *ifo.Ifo
idx *idx.Idx
dict *dict.Dict
dictFile *os.File
ifoPath string
version string
bookname string
wordcount int64
synwordcount int64
idxfilesize int64
idxoffsetbits int64
author string
email string
website string
description string
sametypesequence []dict.DataType
}
// OpenAll opens all dictionaries under a directory. This function will return
// all successfully opened dictionaries along with any errors that occurred.
func OpenAll(path string) ([]*Stardict, []error) {
var dicts []*Stardict
var errs []error
if err := filepath.WalkDir(path, func(path string, info fs.DirEntry, err error) error {
// Walking the file path will ignore errors.
if err != nil {
errs = append(errs, err)
return nil
}
if !info.IsDir() && (filepath.Ext(info.Name()) == ".ifo" || filepath.Ext(info.Name()) == ".IFO") {
dict, err := Open(path)
if err != nil {
errs = append(errs, err)
return nil
}
dicts = append(dicts, dict)
}
return nil
}); err != nil {
errs = append(errs, err)
return nil, errs
}
return dicts, errs
}
// Open opens a Stardict dictionary from the given .ifo file path.
func Open(path string) (*Stardict, error) {
s := &Stardict{
ifoPath: path,
idxoffsetbits: 32,
}
ifoExt := filepath.Ext(s.ifoPath)
if ifoExt != ".ifo" && ifoExt != ".IFO" {
return nil, fmt.Errorf("bad extension: %v", ifoExt)
}
ifoFile, err := os.Open(s.ifoPath)
if err != nil {
return nil, fmt.Errorf("error opening %q: %w", s.ifoPath, err)
}
defer ifoFile.Close()
s.ifo, err = ifo.New(ifoFile)
if err != nil {
return nil, fmt.Errorf("error reading %q: %w", s.ifoPath, err)
}
if s.ifo.Magic() != ifoMagic {
return nil, fmt.Errorf("%q bad magic data", s.ifoPath)
}
// Validate the version
s.version = s.ifo.Value("version")
switch s.version {
case "2.4.2":
case "3.0.0":
default:
return nil, fmt.Errorf("invalid version: %v", s.version)
}
s.bookname = s.ifo.Value("bookname")
if s.bookname == "" {
return nil, fmt.Errorf("missing bookname")
}
s.wordcount, err = strconv.ParseInt(s.ifo.Value("wordcount"), 10, 64)
if err != nil {
return nil, fmt.Errorf("bad wordcount: %w", err)
}
s.idxfilesize, err = strconv.ParseInt(s.ifo.Value("idxfilesize"), 10, 64)
if err != nil {
return nil, fmt.Errorf("bad idxfilesize: %w", err)
}
idxoffsetbits := s.ifo.Value("idxoffsetbits")
if idxoffsetbits != "" && s.version == "3.0.0" {
s.idxoffsetbits, err = strconv.ParseInt(idxoffsetbits, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid idxoffsetbits: %w", err)
}
}
synwordcount := s.ifo.Value("synwordcount")
if synwordcount != "" {
s.synwordcount, err = strconv.ParseInt(synwordcount, 10, 64)
if err != nil {
return nil, fmt.Errorf("bad synwordcount: %w", err)
}
}
sametypesequence := s.ifo.Value("sametypesequence")
if sametypesequence != "" {
for _, r := range sametypesequence {
s.sametypesequence = append(s.sametypesequence, dict.DataType(r))
}
}
s.author = s.ifo.Value("author")
s.email = s.ifo.Value("email")
s.description = s.ifo.Value("description")
s.website = s.ifo.Value("website")
// TODO: support the .syn file.
// TODO: support the .tdx file.
// TODO: support resource storage
return s, nil
}
// Bookname returns the dictionary name.
func (s *Stardict) Bookname() string {
return s.bookname
}
// Description returns the dictionary description.
func (s *Stardict) Description() string {
return s.description
}
// Author returns the dictionary author.
func (s *Stardict) Author() string {
return s.author
}
// Email returns the dictionary contact email.
func (s *Stardict) Email() string {
return s.email
}
// Website returns the dictionary website url.
func (s *Stardict) Website() string {
return s.website
}
// WordCount returns the dictionary word count.
func (s *Stardict) WordCount() int64 {
return s.wordcount
}
// Version returns the dictionary format version.
func (s *Stardict) Version() string {
return s.version
}
// Search performs a simple full text search of the dictionary for the
// given query and returns dictionary entries.
func (s *Stardict) Search(query string) ([]*Entry, error) {
idx, err := s.Index()
if err != nil {
return nil, err
}
dict, err := s.Dict()
if err != nil {
return nil, err
}
var entries []*Entry
for _, idxWord := range idx.FullTextSearch(query) {
dictWord, err := dict.Word(idxWord)
if err != nil {
return nil, err
}
entries = append(entries, &Entry{
word: idxWord.Word,
data: dictWord.Data,
})
}
return entries, nil
}
// IndexScanner returns a new index scanner. The caller assumes ownership of
// the underlying reader so Close should be called on the scanner when
// finished.
func (s *Stardict) IndexScanner() (*idx.Scanner, error) {
f, err := s.openIdxFile()
if err != nil {
return nil, err
}
return idx.NewScanner(f, s.idxoffsetbits)
}
// Index returns a simple in-memory version of the dictionary's index.
func (s *Stardict) Index() (*idx.Idx, error) {
if s.idx != nil {
return s.idx, nil
}
if err := s.openIdx(); err != nil {
return nil, err
}
return s.idx, nil
}
// Dict returns the dictionary's dict.
func (s *Stardict) Dict() (*dict.Dict, error) {
if s.dict != nil {
return s.dict, nil
}
// Open the dict file.
if err := s.openDict(); err != nil {
return nil, err
}
return s.dict, nil
}
// Close closes the dict and any underlying readers.
func (s *Stardict) Close() error {
if s.dictFile != nil {
return s.dictFile.Close()
}
return nil
}
func (s *Stardict) openIdxFile() (*os.File, error) {
ifoExt := filepath.Ext(s.ifoPath)
baseName := strings.TrimSuffix(s.ifoPath, ifoExt)
idxExts := []string{".idx.gz", ".idx", ".IDX", ".IDX.gz", ".IDX.GZ"}
var idxPath string
for _, ext := range idxExts {
idxPath = baseName + ext
if _, err := os.Stat(idxPath); err == nil {
break
}
}
if idxPath == "" {
return nil, fmt.Errorf("no .idx file found")
}
return os.Open(idxPath)
}
func (s *Stardict) openIdx() error {
var r io.ReadCloser
var err error
f, err := s.openIdxFile()
if err != nil {
return err
}
defer f.Close()
idxPath := f.Name()
r = f
idxExt := filepath.Ext(idxPath)
if strings.ToLower(idxExt) == ".gz" {
r, err = gzip.NewReader(r)
if err != nil {
return fmt.Errorf("error opening %q: %w", idxPath, err)
}
defer r.Close()
}
idx, err := idx.New(r, s.idxoffsetbits)
if err != nil {
return fmt.Errorf("error reading %q: %w", idxPath, err)
}
s.idx = idx
return nil
}
func (s *Stardict) openDict() error {
ifoExt := filepath.Ext(s.ifoPath)
baseName := strings.TrimSuffix(s.ifoPath, ifoExt)
dictExts := []string{".dict.dz", ".dict", ".DICT", ".DICT.dz", ".DICT.DZ"}
var dictPath string
for _, ext := range dictExts {
dictPath = baseName + ext
if _, err := os.Stat(dictPath); err == nil {
break
}
}
if dictPath == "" {
return fmt.Errorf("no dict found")
}
var r io.ReaderAt
f, err := os.Open(dictPath)
if err != nil {
return fmt.Errorf("error opening %q: %w", dictPath, err)
}
r = f
var dz *dictzip.Reader
dictExt := filepath.Ext(dictPath)
if strings.ToLower(dictExt) == ".dz" {
dz, err = dictzip.NewReader(f)
if err != nil {
return err
}
r = dz
}
dict, err := dict.New(r, s.sametypesequence)
if err != nil {
return fmt.Errorf("error reading %q: %w", dictPath, err)
}
s.dict = dict
s.dictFile = f
return nil
}