whatsapp-backend-test / services /chat_service.go
RyZ
fix: add secure atribute to cookies
b0b934b
package services
import (
"context"
"whatsapp-backend/models/dto"
http_error "whatsapp-backend/models/error"
"whatsapp-backend/repositories"
"github.com/google/uuid"
)
type ChatService interface {
FetchContacts(ctx context.Context, accountID uuid.UUID) ([]dto.ContactResponse, error)
SendMessage(ctx context.Context, accountID uuid.UUID, recipient string, message string) (string, error)
SendImage(ctx context.Context, accountID uuid.UUID, recipient string, imageData []byte, mimetype string, caption string) (string, error)
}
type chatService struct {
connectionService ConnectionService
chatRepository repositories.ChatRepository
}
func NewChatService(connectionService ConnectionService, chatRepository repositories.ChatRepository) ChatService {
return &chatService{
connectionService: connectionService,
chatRepository: chatRepository,
}
}
func (s *chatService) FetchContacts(ctx context.Context, accountID uuid.UUID) ([]dto.ContactResponse, error) {
client, err := s.connectionService.GetActiveClient(accountID)
if err != nil {
return nil, err
}
if !client.IsConnected() {
return nil, http_error.ERR_CLIENT_NOT_CONNECTED
}
contacts, err := s.chatRepository.FetchContacts(ctx, client)
if err != nil {
return nil, err
}
var response []dto.ContactResponse
for jid, contact := range contacts {
response = append(response, dto.ContactResponse{
JID: jid.String(),
Name: contact.FirstName,
FullName: contact.FullName,
PushName: contact.PushName,
PhoneNumber: jid.User,
})
}
return response, nil
}
func (s *chatService) SendMessage(ctx context.Context, accountID uuid.UUID, recipient string, message string) (string, error) {
client, err := s.connectionService.GetActiveClient(accountID)
if err != nil {
return "", err
}
if !client.IsConnected() {
return "", http_error.ERR_CLIENT_NOT_CONNECTED
}
msgID, err := s.chatRepository.SendMessage(ctx, client, recipient, message)
if err != nil {
return "", err
}
return msgID, nil
}
func (s *chatService) SendImage(ctx context.Context, accountID uuid.UUID, recipient string, imageData []byte, mimetype string, caption string) (string, error) {
client, err := s.connectionService.GetActiveClient(accountID)
if err != nil {
return "", err
}
if !client.IsConnected() {
return "", http_error.ERR_CLIENT_NOT_CONNECTED
}
msgID, err := s.chatRepository.SendImage(ctx, client, recipient, imageData, mimetype, caption)
if err != nil {
return "", err
}
return msgID, nil
}