-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathattachments.go
More file actions
178 lines (155 loc) · 3.88 KB
/
Copy pathattachments.go
File metadata and controls
178 lines (155 loc) · 3.88 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
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
// Package main handles attachment metadata persistence and text extraction.
package main
import (
"database/sql"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
"example.org/dc-logger/internal/config"
"github.com/bwmarrin/discordgo"
)
var (
attachmentHTTPClient = &http.Client{Timeout: 20 * time.Second}
attachmentTextFetcher = fetchAttachmentText
attachmentTextMaxBytesOnce sync.Once
attachmentTextMaxBytes int
)
const attachmentLogMaxChars = 2000
func upsertMessageAttachments(
stmt *sql.Stmt,
attachments []*discordgo.MessageAttachment,
guildID, channelID, messageID, authorID, createdAt, now string,
rel messageRelationship,
) (int, string) {
if stmt == nil || len(attachments) == 0 {
return 0, ""
}
var inserted int
logParts := make([]string, 0, len(attachments))
for _, a := range attachments {
if a == nil || a.ID == "" {
continue
}
contentText := ""
if shouldExtractAttachmentText(a) && a.URL != "" {
text, err := attachmentTextFetcher(a.URL, getAttachmentTextMaxBytes())
if err != nil {
log.Printf("attachment text fetch failed (attachment=%s message=%s): %v", a.ID, messageID, err)
} else {
contentText = text
}
}
if _, err := stmt.Exec(
a.ID,
messageID,
guildID,
channelID,
authorID,
createdAt,
a.Filename,
a.ContentType,
a.Size,
a.URL,
a.ProxyURL,
contentText,
rel.referencedMessageID,
rel.referencedChannelID,
rel.referencedGuildID,
rel.threadID,
rel.threadParentID,
now,
"",
); err != nil {
logDBErr("attachment upsert failed (attachment=%s message=%s): %v", a.ID, messageID, err)
continue
}
inserted++
if text := strings.TrimSpace(contentText); text != "" {
logParts = append(logParts, text)
continue
}
if name := strings.TrimSpace(a.Filename); name != "" {
logParts = append(logParts, "[attachment] "+name)
}
}
return inserted, summarizeAttachmentLogContent(logParts)
}
func summarizeAttachmentLogContent(parts []string) string {
if len(parts) == 0 {
return ""
}
combined := strings.Join(parts, "\n\n")
if len(combined) <= attachmentLogMaxChars {
return combined
}
return combined[:attachmentLogMaxChars] + "\n...[truncated in log; full attachment text stored in DB]"
}
func shouldExtractAttachmentText(a *discordgo.MessageAttachment) bool {
if a == nil {
return false
}
filename := strings.ToLower(a.Filename)
contentType := strings.ToLower(a.ContentType)
if strings.HasPrefix(contentType, "text/") {
return true
}
if contentType == "application/json" {
return true
}
switch {
case strings.HasSuffix(filename, ".txt"),
strings.HasSuffix(filename, ".md"),
strings.HasSuffix(filename, ".log"),
strings.HasSuffix(filename, ".csv"),
strings.HasSuffix(filename, ".json"),
strings.HasSuffix(filename, ".yaml"),
strings.HasSuffix(filename, ".yml"):
return true
default:
return false
}
}
func fetchAttachmentText(url string, maxBytes int) (string, error) {
resp, err := attachmentHTTPClient.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
limit := int64(maxBytes)
if limit <= 0 {
limit = config.DefaultAttachmentTextMaxBytes
}
body, err := io.ReadAll(io.LimitReader(resp.Body, limit))
if err != nil {
return "", err
}
return string(body), nil
}
func getAttachmentTextMaxBytes() int {
attachmentTextMaxBytesOnce.Do(func() {
raw := getenvDefault(
config.EnvDiscordAttachmentTextMaxBytes,
strconv.Itoa(config.DefaultAttachmentTextMaxBytes),
)
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 {
log.Printf(
"invalid %s=%q; using default=%d",
config.EnvDiscordAttachmentTextMaxBytes,
raw,
config.DefaultAttachmentTextMaxBytes,
)
n = config.DefaultAttachmentTextMaxBytes
}
attachmentTextMaxBytes = n
})
return attachmentTextMaxBytes
}