-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathchat_service.go
More file actions
271 lines (221 loc) · 8.87 KB
/
chat_service.go
File metadata and controls
271 lines (221 loc) · 8.87 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package chat_service
import (
"context"
"errors"
"fmt"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/types"
)
type ChatService interface {
ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)
ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)
HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)
}
type chatService struct {
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type BodyStruct struct {
Chat string `json:"chat"`
// Duration is used by mute operations: seconds to mute (0 = mute forever).
Duration int64 `json:"duration,omitempty"`
}
type HistorySyncRequestStruct struct {
MessageInfo *types.MessageInfo `json:"messageInfo"`
Count int `json:"count"`
}
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := c.whatsmeowService.StartInstance(instanceId)
if err != nil {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
return nil, errors.New("no active session found")
}
} else if !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (c *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
// maxMuteDurationSeconds caps mute at 1 year to avoid unreasonably large timestamps.
const maxMuteDurationSeconds = 365 * 24 * 3600
func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
if data.Duration < 0 {
return "", errors.New("duration must be >= 0 (0 = mute forever)")
}
if data.Duration > maxMuteDurationSeconds {
return "", fmt.Errorf("duration exceeds maximum allowed value of %d seconds (1 year)", maxMuteDurationSeconds)
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
// duration=0 is passed as-is: BuildMute treats 0 as "mute forever" (sets timestamp to -1).
muteDuration := time.Duration(data.Duration) * time.Second
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, muteDuration))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
recipient, ok := utils.ParseJID(data.Chat)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)
return "", err
}
return ts.String(), nil
}
func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: data.MessageInfo.Chat,
IsFromMe: data.MessageInfo.IsFromMe,
IsGroup: data.MessageInfo.IsGroup,
},
ID: data.MessageInfo.ID,
Timestamp: data.MessageInfo.Timestamp,
}
histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)
res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)
return nil, err
}
return &res, nil
}
func NewChatService(
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) ChatService {
return &chatService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}