/
attach.go
380 lines (325 loc) · 9.56 KB
/
attach.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
Copyright 2018 The pdfcpu Authors.
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 pdfcpu
import (
"bytes"
"fmt"
"io"
"time"
"github.com/Kush-Wednesday/pdfcpu-custom/pkg/filter"
"github.com/Kush-Wednesday/pdfcpu-custom/pkg/log"
"github.com/pkg/errors"
)
func decodeFileSpecStreamDict(sd *StreamDict, id string) error {
fpl := sd.FilterPipeline
if fpl == nil {
sd.Content = sd.Raw
return nil
}
// Ignore filter chains with length > 1
if len(fpl) > 1 {
log.Debug.Printf("decodedFileSpecStreamDict: ignore %s, more than 1 filter.\n", id)
return nil
}
// Only FlateDecode supported.
if fpl[0].Name != filter.Flate {
log.Debug.Printf("decodedFileSpecStreamDict: ignore %s, %s filter unsupported.\n", id, fpl[0].Name)
return nil
}
// Decode streamDict for supported filters only.
return sd.Decode()
}
func fileSpectStreamFileName(xRefTable *XRefTable, d Dict) (string, error) {
o, found := d.Find("UF")
if found {
fileName, err := xRefTable.DereferenceStringOrHexLiteral(o, V10, nil)
return fileName, err
}
o, found = d.Find("F")
if !found {
return "", errors.New("")
}
fileName, err := xRefTable.DereferenceStringOrHexLiteral(o, V10, nil)
return fileName, err
}
func fileSpecStreamDict(xRefTable *XRefTable, d Dict) (*StreamDict, error) {
// Entry EF is a dict holding a stream dict in entry F.
o, found := d.Find("EF")
if !found || o == nil {
return nil, nil
}
d, err := xRefTable.DereferenceDict(o)
if err != nil || o == nil {
return nil, err
}
// Entry F holds the embedded file's data.
o, found = d.Find("F")
if !found || o == nil {
return nil, nil
}
sd, _, err := xRefTable.DereferenceStreamDict(o)
return sd, err
}
func fileSpecStreamDictInfo(xRefTable *XRefTable, id string, o Object, decode bool) (*StreamDict, string, string, *time.Time, error) {
d, err := xRefTable.DereferenceDict(o)
if err != nil {
return nil, "", "", nil, err
}
var desc string
o, found := d.Find("Desc")
if found {
desc, err = xRefTable.DereferenceStringOrHexLiteral(o, V10, nil)
if err != nil {
return nil, "", "", nil, err
}
}
fileName, err := fileSpectStreamFileName(xRefTable, d)
if err != nil {
return nil, "", "", nil, err
}
sd, err := fileSpecStreamDict(xRefTable, d)
if err != nil {
return nil, "", "", nil, err
}
var modDate *time.Time
if d = sd.DictEntry("Params"); d != nil {
if s := d.StringEntry("ModDate"); s != nil {
dt, ok := DateTime(*s, xRefTable.ValidationMode == ValidationRelaxed)
if !ok {
return nil, desc, "", nil, errors.New("pdfcpu: invalid date ModDate")
}
modDate = &dt
}
}
err = decodeFileSpecStreamDict(sd, id)
return sd, desc, fileName, modDate, err
}
// Attachment is a Reader representing a PDF attachment.
type Attachment struct {
io.Reader // attachment data
ID string // id
FileName string // filename
Desc string // description
ModTime *time.Time // time of last modification (optional)
}
func (a Attachment) String() string {
return fmt.Sprintf("Attachment: id:%s desc:%s modTime:%s", a.ID, a.Desc, a.ModTime)
}
// ListAttachments returns a slice of attachment stubs (attachment w/o data).
func (ctx *Context) ListAttachments() ([]Attachment, error) {
xRefTable := ctx.XRefTable
if !xRefTable.Valid {
if err := xRefTable.LocateNameTree("EmbeddedFiles", false); err != nil {
return nil, err
}
}
if xRefTable.Names["EmbeddedFiles"] == nil {
return nil, nil
}
aa := []Attachment{}
createAttachmentStub := func(xRefTable *XRefTable, id string, o Object) error {
decode := false
_, desc, fileName, modTime, err := fileSpecStreamDictInfo(xRefTable, id, o, decode)
if err != nil {
return err
}
aa = append(aa, Attachment{nil, id, fileName, desc, modTime})
return nil
}
// Extract stub info.
if err := ctx.Names["EmbeddedFiles"].Process(xRefTable, createAttachmentStub); err != nil {
return nil, err
}
return aa, nil
}
// AddAttachment adds a.
func (ctx *Context) AddAttachment(a Attachment, useCollection bool) error {
xRefTable := ctx.XRefTable
if err := xRefTable.LocateNameTree("EmbeddedFiles", true); err != nil {
return err
}
if useCollection {
// Ensure a Collection entry in the catalog.
if err := xRefTable.EnsureCollection(); err != nil {
return err
}
}
ir, err := xRefTable.NewFileSpectDictForAttachment(a)
if err != nil {
return err
}
return xRefTable.Names["EmbeddedFiles"].Add(xRefTable, EncodeUTF16String(a.ID), *ir)
}
var errContentMatch = errors.New("name tree content match")
// SearchEmbeddedFilesNameTreeNodeByContent tries to identify a name tree by content.
func (ctx *Context) SearchEmbeddedFilesNameTreeNodeByContent(s string) (*string, Object, error) {
var (
k *string
v Object
)
identifyAttachmentStub := func(xRefTable *XRefTable, id string, o Object) error {
decode := false
_, desc, fileName, _, err := fileSpecStreamDictInfo(xRefTable, id, o, decode)
if err != nil {
return err
}
if s == fileName || s == desc {
k = &id
v = o
return errContentMatch
}
return nil
}
if err := ctx.Names["EmbeddedFiles"].Process(ctx.XRefTable, identifyAttachmentStub); err != nil {
if err != errContentMatch {
return nil, nil, err
}
// Node identified.
return k, v, nil
}
return nil, nil, nil
}
func (ctx *Context) removeAttachment(id string) (bool, error) {
log.CLI.Printf("removing %s\n", id)
xRefTable := ctx.XRefTable
// EmbeddedFiles name tree containing at least one key value pair.
empty, ok, err := xRefTable.Names["EmbeddedFiles"].Remove(xRefTable, id)
if err != nil {
return false, err
}
if empty {
// Delete name tree root object.
if err := xRefTable.RemoveEmbeddedFilesNameTree(); err != nil {
return false, err
}
}
if !ok {
// Try to identify name tree node by content.
k, _, err := ctx.SearchEmbeddedFilesNameTreeNodeByContent(id)
if err != nil {
return false, err
}
if k == nil {
log.CLI.Printf("attachment %s not found", id)
return false, nil
}
empty, _, err = xRefTable.Names["EmbeddedFiles"].Remove(xRefTable, *k)
if err != nil {
return false, err
}
if empty {
// Delete name tree root object.
if err := xRefTable.RemoveEmbeddedFilesNameTree(); err != nil {
return false, err
}
}
}
return true, nil
}
// RemoveAttachments removes attachments with given id and returns true if anything removed.
func (ctx *Context) RemoveAttachments(ids []string) (bool, error) {
// Note: Any remove operation may be deleting the only key value pair of this name tree.
xRefTable := ctx.XRefTable
if !xRefTable.Valid {
if err := xRefTable.LocateNameTree("EmbeddedFiles", false); err != nil {
return false, err
}
}
if xRefTable.Names["EmbeddedFiles"] == nil {
return false, errors.Errorf("no attachments available.")
}
if len(ids) == 0 {
// Remove all attachments - delete name tree root object.
log.CLI.Println("removing all attachments")
if err := xRefTable.RemoveEmbeddedFilesNameTree(); err != nil {
return false, err
}
return true, nil
}
for _, id := range ids {
found, err := ctx.removeAttachment(id)
if err != nil {
return false, err
}
if !found {
return false, nil
}
}
return true, nil
}
// RemoveAttachment removes a and returns true on success.
func (ctx *Context) RemoveAttachment(a Attachment) (bool, error) {
return ctx.RemoveAttachments([]string{a.ID})
}
// ExtractAttachments extracts attachments with id.
func (ctx *Context) ExtractAttachments(ids []string) ([]Attachment, error) {
xRefTable := ctx.XRefTable
if !xRefTable.Valid {
if err := xRefTable.LocateNameTree("EmbeddedFiles", false); err != nil {
return nil, err
}
}
if xRefTable.Names["EmbeddedFiles"] == nil {
return nil, errors.Errorf("no attachments available.")
}
aa := []Attachment{}
createAttachment := func(xRefTable *XRefTable, id string, o Object) error {
decode := true
sd, desc, fileName, modTime, err := fileSpecStreamDictInfo(xRefTable, id, o, decode)
if err != nil {
return err
}
a := Attachment{Reader: bytes.NewReader(sd.Content), ID: id, FileName: fileName, Desc: desc, ModTime: modTime}
aa = append(aa, a)
return nil
}
// Search with UF,F,Desc
if len(ids) > 0 {
for _, id := range ids {
v, ok := ctx.Names["EmbeddedFiles"].Value(id)
if !ok {
// Try to identify name tree node by content.
k, o, err := ctx.SearchEmbeddedFilesNameTreeNodeByContent(id)
if err != nil {
return nil, err
}
if k == nil {
log.CLI.Printf("attachment %s not found", id)
log.Info.Printf("pdfcpu: extractAttachments: %s not found", id)
continue
}
v = o
}
if err := createAttachment(ctx.XRefTable, id, v); err != nil {
return nil, err
}
}
return aa, nil
}
// Extract all files.
if err := ctx.Names["EmbeddedFiles"].Process(ctx.XRefTable, createAttachment); err != nil {
return nil, err
}
return aa, nil
}
// ExtractAttachment extracts a fully populated attachment.
func (ctx *Context) ExtractAttachment(a Attachment) (*Attachment, error) {
aa, err := ctx.ExtractAttachments([]string{a.ID})
if err != nil || len(aa) == 0 {
return nil, err
}
if len(aa) > 1 {
return nil, errors.Errorf("pdfcpu: unexpected number of attachments: %d", len(aa))
}
return &aa[0], nil
}