-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathattachment.go
More file actions
107 lines (82 loc) · 2.46 KB
/
attachment.go
File metadata and controls
107 lines (82 loc) · 2.46 KB
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
package wordpress
import (
"go.opencensus.io/trace"
"github.com/wulijun/go-php-serialize/phpserialize"
"golang.org/x/net/context"
)
// Attachment represents a WordPress attachment
type Attachment struct {
Object
FileName string `json:"file_name"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Caption string `json:"caption"`
AltText string `json:"alt_text"`
Url string `json:"url,omitempty"`
}
// GetAttachments gets all attachment data from the database
func GetAttachments(c context.Context, attachmentIds ...int64) ([]*Attachment, error) {
c, span := trace.StartSpan(c, "/wordpress.GetAttachments")
defer span.End()
if len(attachmentIds) == 0 {
return nil, nil
}
ids, idMap := dedupe(attachmentIds)
objects, err := getObjects(c, ids...)
if err != nil {
return nil, err
}
baseUrl, _ := GetOption(c, "upload_url_path")
if baseUrl == "" {
siteUrl, _ := GetOption(c, "siteurl")
baseDir, _ := GetOption(c, "upload_path")
if baseDir == "" {
baseDir = "/wp-content/uploads"
}
baseUrl = siteUrl + baseDir
}
ret := make([]*Attachment, len(attachmentIds))
for _, obj := range objects {
att := Attachment{Object: *obj}
meta, err := att.GetMeta(c, "_wp_attachment_metadata")
if err != nil {
return nil, err
}
if enc, ok := meta["_wp_attachment_metadata"]; ok && enc != "" {
if dec, err := phpserialize.Decode(enc); err == nil {
if meta, ok := dec.(map[interface{}]interface{}); ok {
if file, ok := meta["file"].(string); ok {
att.FileName = file
}
if width, ok := meta["width"].(int64); ok {
att.Width = int(width)
}
if height, ok := meta["height"].(int64); ok {
att.Height = int(height)
}
if imageMeta, ok := meta["image_meta"].(map[interface{}]interface{}); ok {
if caption, ok := imageMeta["caption"].(string); ok {
att.Caption = caption
}
if alt, ok := imageMeta["title"].(string); ok {
att.AltText = alt
}
}
}
}
}
att.Url = baseUrl + att.Date.Format("/2006/01/") + att.FileName
// insert into return set
for _, index := range idMap[att.Id] {
ret[index] = &att
}
}
return ret, nil
}
// QueryAttachments returns the ids of the attachments that match the query
func QueryAttachments(c context.Context, opts *ObjectQueryOptions) (Iterator, error) {
c, span := trace.StartSpan(c, "/wordpress.QueryAttachments")
defer span.End()
opts.PostType = PostTypeAttachment
return queryObjects(c, opts)
}