-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediahandler.go
111 lines (100 loc) · 2.64 KB
/
mediahandler.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
package main
import (
"fmt"
"log"
"time"
)
type MediaItem struct {
GroupID string
ChatID int64
Caption string
URL string
ReplyToMessageID int
}
type MediaGroup struct {
GroupID string
ChatID int64
Caption string
URLs []string
LastUpdate time.Time
ChatGPTResponse *OpenAIResponse
ChatGPTError error
ReplyToMessageID int
}
type MediaHandler struct {
InputChannel chan *MediaItem
internalChannel chan *MediaGroup
OutputChannel chan *MediaGroup
}
func NewMediaHandler() *MediaHandler {
mh := &MediaHandler{
InputChannel: make(chan *MediaItem),
internalChannel: make(chan *MediaGroup),
OutputChannel: make(chan *MediaGroup),
}
go mh.mediaConsolidator()
go mh.mediaDownloader()
return mh
}
func (m *MediaHandler) mediaDownloader() {
for mg := range m.internalChannel {
log.Printf("asking ChatGPT about group '%s' with %d images", mg.GroupID, len(mg.URLs))
response, err := AskOpenAI(mg.Caption, mg.URLs)
if err != nil {
mg.ChatGPTError = err
} else {
mg.ChatGPTResponse = response
}
log.Printf("ChatGPT response: %v", mg.ChatGPTResponse)
m.OutputChannel <- mg
}
}
func (m *MediaHandler) mediaConsolidator() {
incoming := make(map[string]*MediaGroup)
timer := time.NewTicker(time.Second)
threshold := time.Second
for {
select {
case message := <-m.InputChannel:
log.Printf("received image")
if message.GroupID == "" {
fmt.Println("consolidating single image")
m.internalChannel <- &MediaGroup{
GroupID: "",
ChatID: message.ChatID,
Caption: message.Caption,
URLs: []string{message.URL},
LastUpdate: time.Now(),
ReplyToMessageID: message.ReplyToMessageID,
}
continue
} else {
if group, ok := incoming[message.GroupID]; ok {
group.URLs = append(group.URLs, message.URL)
group.LastUpdate = time.Now()
// Use the first message's ID for reply
if group.ReplyToMessageID == 0 {
group.ReplyToMessageID = message.ReplyToMessageID
}
} else {
incoming[message.GroupID] = &MediaGroup{
GroupID: message.GroupID,
ChatID: message.ChatID,
Caption: message.Caption,
URLs: []string{message.URL},
LastUpdate: time.Now(),
ReplyToMessageID: message.ReplyToMessageID,
}
}
}
case <-timer.C:
for groupID, group := range incoming {
if time.Since(group.LastUpdate) >= threshold {
log.Printf("consolidating group %s", groupID)
m.internalChannel <- group
delete(incoming, groupID)
}
}
}
}
}