-
Notifications
You must be signed in to change notification settings - Fork 1
/
openmessaging_attachment.go
89 lines (79 loc) · 2.43 KB
/
openmessaging_attachment.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
package gcloudcx
import (
"encoding/json"
"mime"
"net/url"
"path"
"strings"
"github.com/gildas/go-core"
"github.com/gildas/go-errors"
"github.com/gildas/go-request"
nanoid "github.com/matoous/go-nanoid/v2"
)
type OpenMessageAttachment struct {
ID string `json:"id,omitempty"`
Type string `json:"mediaType"`
URL *url.URL `json:"-"`
Mime string `json:"mime,omitempty"`
Filename string `json:"filename,omitempty"`
Length uint64 `json:"contentSizeBytes,omitempty"`
Text string `json:"text,omitempty"`
Hash string `json:"sha256,omitempty"`
}
func (attachment OpenMessageAttachment) WithContent(content *request.Content) *OpenMessageAttachment {
var attachmentType string
switch {
case len(content.Type) == 0:
attachmentType = "Link"
case strings.HasPrefix(content.Type, "audio"):
attachmentType = "Audio"
case strings.HasPrefix(content.Type, "image"):
attachmentType = "Image"
case strings.HasPrefix(content.Type, "video"):
attachmentType = "Video"
default:
attachmentType = "File"
}
attachment.Type = attachmentType
attachment.Mime = content.Type
attachment.Filename = content.Name
attachment.URL = content.URL
attachment.Length = content.Length
if attachmentType != "Link" && len(content.Name) == 0 {
fileExtension := path.Ext(content.URL.Path)
if content.Type == "audio/mpeg" {
fileExtension = ".mp3"
} else if fileExtensions, err := mime.ExtensionsByType(content.Type); err == nil && len(fileExtensions) > 0 {
fileExtension = fileExtensions[0]
}
fileID, _ := nanoid.New()
attachment.Filename = strings.ToLower(attachmentType) + "-" + fileID + fileExtension
}
return &attachment
}
// MarshalJSON marshals this into JSON
func (attachment OpenMessageAttachment) MarshalJSON() ([]byte, error) {
type surrogate OpenMessageAttachment
data, err := json.Marshal(struct {
surrogate
U *core.URL `json:"url"`
}{
surrogate: surrogate(attachment),
U: (*core.URL)(attachment.URL),
})
return data, errors.JSONMarshalError.Wrap(err)
}
// UnmarshalJSON unmarshals JSON into this
func (attachment *OpenMessageAttachment) UnmarshalJSON(payload []byte) (err error) {
type surrogate OpenMessageAttachment
var inner struct {
surrogate
U *core.URL `json:"url"`
}
if err = json.Unmarshal(payload, &inner); err != nil {
return errors.JSONUnmarshalError.Wrap(err)
}
*attachment = OpenMessageAttachment(inner.surrogate)
attachment.URL = (*url.URL)(inner.U)
return
}