-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.go
73 lines (61 loc) · 1.44 KB
/
files.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
package objects
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"strings"
)
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
type DiscordFile struct {
*bytes.Buffer
Filename string
Description string
ContentType string
Spoiler bool
}
func NewDiscordFile(r io.Reader, filename, description string) (*DiscordFile, error) {
f := &DiscordFile{
Buffer: &bytes.Buffer{},
Filename: filename,
Description: description,
}
_, err := io.Copy(f.Buffer, r)
if err != nil {
return nil, err
}
return f, nil
}
const formFieldNameFmt = "files[%d]"
func (f *DiscordFile) GenerateAttachment(index Snowflake, m *multipart.Writer) (*Attachment, error) {
if f.Spoiler && !strings.HasPrefix(f.Filename, "SPOILER_") {
f.Filename = "SPOILER_" + f.Filename
}
a := &Attachment{
ID: index,
Filename: f.Filename,
Description: f.Description,
}
contentType := "application/octet-stream"
if f.ContentType != "" {
contentType = f.ContentType
}
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
escapeQuotes(fmt.Sprintf(formFieldNameFmt, index)), escapeQuotes(f.Filename)))
h.Set("Content-Type", contentType)
w, err := m.CreatePart(h)
if err != nil {
return nil, err
}
_, err = io.Copy(w, f)
if err != nil {
return nil, err
}
return a, nil
}