Spaces:
Paused
Paused
File size: 12,104 Bytes
83a59ca | 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | package services
import (
"context"
"fmt"
"sync"
"time"
"github.com/NdoleStudio/httpsms/pkg/events"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/gofiber/fiber/v3"
"github.com/NdoleStudio/httpsms/pkg/discord"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/NdoleStudio/stacktrace"
"github.com/google/uuid"
)
// DiscordService is responsible for handling discordIntegrations
type DiscordService struct {
service
logger telemetry.Logger
tracer telemetry.Tracer
client *discord.Client
dispatcher *EventDispatcher
repository repositories.DiscordRepository
}
// NewDiscordService creates a new DiscordService
func NewDiscordService(
logger telemetry.Logger,
tracer telemetry.Tracer,
client *discord.Client,
repository repositories.DiscordRepository,
dispatcher *EventDispatcher,
) (s *DiscordService) {
return &DiscordService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
tracer: tracer,
client: client,
dispatcher: dispatcher,
repository: repository,
}
}
// GetByServerID fetches the entities.Discord by the serverID
func (service *DiscordService) GetByServerID(ctx context.Context, serverID string) (*entities.Discord, error) {
ctx, span, _ := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
return service.repository.FindByServerID(ctx, serverID)
}
// DeleteAllForUser deletes all entities.Discord for an entities.UserID.
func (service *DiscordService) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
if err := service.repository.DeleteAllForUser(ctx, userID); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not delete all [entities.Discord] for user with ID [%s]", userID))
}
ctxLogger.Info(fmt.Sprintf("deleted all [entities.Discord] for user with ID [%s]", userID))
return nil
}
// Index fetches the entities.Discord for an entities.UserID
func (service *DiscordService) Index(ctx context.Context, userID entities.UserID, params repositories.IndexParams) ([]*entities.Discord, error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
discordIntegrations, err := service.repository.Index(ctx, userID, params)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not fetch discord integrations with params [%+#v]", params))
}
ctxLogger.Info(fmt.Sprintf("fetched [%d] discord integrations with prams [%+#v]", len(discordIntegrations), params))
return discordIntegrations, nil
}
// Delete an entities.Discord
func (service *DiscordService) Delete(ctx context.Context, userID entities.UserID, discordID uuid.UUID) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
if _, err := service.repository.Load(ctx, userID, discordID); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load discord integration with userID [%s] and discordID [%s]", userID, discordID))
}
if err := service.repository.Delete(ctx, userID, discordID); err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete discord integration with id [%s] and discordID [%s]", discordID, userID))
}
ctxLogger.Info(fmt.Sprintf("deleted discord integration with id [%s] and user id [%s]", discordID, userID))
return nil
}
// DiscordStoreParams are parameters for creating a new entities.Discord
type DiscordStoreParams struct {
UserID entities.UserID
Name string
ServerID string
IncomingChannelID string
}
// Store a new entities.Discord
func (service *DiscordService) Store(ctx context.Context, params *DiscordStoreParams) (*entities.Discord, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
if err := service.createSlashCommand(ctx, params.ServerID); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create slash command for server [%s]", params.ServerID))
}
discordIntegration := &entities.Discord{
ID: uuid.New(),
UserID: params.UserID,
Name: params.Name,
ServerID: params.ServerID,
IncomingChannelID: params.IncomingChannelID,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
}
if err := service.repository.Save(ctx, discordIntegration); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot save discord integration with id [%s]", discordIntegration.ID))
}
ctxLogger.Info(fmt.Sprintf("discord integration saved with id [%s] in the [%T]", discordIntegration.ID, service.repository))
return discordIntegration, nil
}
func (service *DiscordService) createSlashCommand(ctx context.Context, serverID string) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
command, _, err := service.client.Application.CreateCommand(ctx, serverID, &discord.CommandCreateRequest{
Name: "httpsms",
Type: 1,
Description: "Send an SMS via httpsms.com",
Options: []discord.CommandCreateRequestOption{
{
Name: "from",
Description: "Sender phone number",
Type: 3,
Required: true,
},
{
Name: "to",
Description: "Recipient phone number",
Type: 3,
Required: true,
},
{
Name: "message",
Description: "Text message content",
Type: 3,
Required: true,
},
{
Name: "attachment_urls",
Description: "Comma-separated list of media URLs to attach",
Type: 3,
Required: false,
},
},
})
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create slash command for server [%s]", serverID))
}
ctxLogger.Info(fmt.Sprintf("upserted a slash command with ID [%s] for discord server [%s] and applicationID [%s]", command.ID, serverID, command.ApplicationID))
return nil
}
// DiscordUpdateParams are parameters for updating an entities.Discord
type DiscordUpdateParams struct {
UserID entities.UserID
Name string
ServerID string
IncomingChannelID string
DiscordID uuid.UUID
}
// Update an entities.Discord
func (service *DiscordService) Update(ctx context.Context, params *DiscordUpdateParams) (*entities.Discord, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
discordIntegration, err := service.repository.Load(ctx, params.UserID, params.DiscordID)
if err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load discord integration with userID [%s] and discordID [%s]", params.UserID, params.DiscordID))
}
if err = service.createSlashCommand(ctx, params.ServerID); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create slash command for server [%s]", params.ServerID))
}
discordIntegration.Name = params.Name
discordIntegration.ServerID = params.ServerID
discordIntegration.IncomingChannelID = params.IncomingChannelID
if err = service.repository.Save(ctx, discordIntegration); err != nil {
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot save discord integration with id [%s] after update", discordIntegration.ID))
}
ctxLogger.Info(fmt.Sprintf("discord integration updated with id [%s] in the [%T]", discordIntegration.ID, service.repository))
return discordIntegration, nil
}
// HandleMessageReceived sends an incoming SMS to a discord channel
func (service *DiscordService) HandleMessageReceived(ctx context.Context, userID entities.UserID, event cloudevents.Event) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
discordIntegrations, err := service.repository.FetchHavingIncomingChannel(ctx, userID)
if err != nil {
return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load discord integrations for user with ID [%s]", userID))
}
if len(discordIntegrations) == 0 {
ctxLogger.Info(fmt.Sprintf("user [%s] has no discord integration for event [%s]", userID, event.Type()))
return nil
}
var wg sync.WaitGroup
for _, discordIntegration := range discordIntegrations {
wg.Add(1)
go func(webhook *entities.Discord) {
defer wg.Done()
service.sendMessage(ctx, event, webhook)
}(discordIntegration)
}
wg.Wait()
return nil
}
func (service *DiscordService) sendMessage(ctx context.Context, event cloudevents.Event, discord *entities.Discord) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
payload := new(events.MessagePhoneReceivedPayload)
if err := event.DataAs(payload); err != nil {
ctxLogger.Error(stacktrace.Propagatef(err, "cannot unmarshal event [%s] with ID [%s] into [%T]", event.Type(), event.ID(), payload))
return
}
request := service.createDiscordMessage(ctxLogger, payload)
message, response, err := service.client.Channel.CreateMessage(ctx, discord.IncomingChannelID, request)
if err != nil {
ctxLogger.Warn(service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot send [%s] event to discord channel [%s] for user [%s]", event.Type(), discord.IncomingChannelID, discord.UserID)))
eventPayload := &events.DiscordSendFailedPayload{
DiscordID: discord.ID,
UserID: discord.UserID,
MessageID: payload.MessageID,
Owner: payload.Owner,
EventType: event.Type(),
ErrorMessage: err.Error(),
DiscordChannelID: discord.IncomingChannelID,
}
if response != nil {
eventPayload.HTTPResponseStatusCode = &response.HTTPResponse.StatusCode
eventPayload.ErrorMessage = string(*response.Body)
}
service.handleDiscordMessageFailed(ctx, event.Source(), eventPayload)
return
}
ctxLogger.Info(fmt.Sprintf("sent discord message [%s] to channel [%s] for [%s] event with ID [%s]", message["id"].(string), discord.IncomingChannelID, event.Type(), event.ID()))
}
func (service *DiscordService) createDiscordMessage(ctxLogger telemetry.Logger, payload *events.MessagePhoneReceivedPayload) fiber.Map {
return fiber.Map{
"content": "✉ new message received",
"embeds": []fiber.Map{
{
"fields": []fiber.Map{
{
"name": "From:",
"value": service.getFormattedNumber(ctxLogger, payload.Contact),
"inline": true,
},
{
"name": "To:",
"value": service.getFormattedNumber(ctxLogger, payload.Owner),
"inline": true,
},
{
"name": "Content:",
"value": payload.Content,
},
{
"name": "MessageID:",
"value": payload.MessageID,
},
},
},
},
}
}
func (service *DiscordService) handleDiscordMessageFailed(ctx context.Context, source string, payload *events.DiscordSendFailedPayload) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
event, err := service.createEvent(events.EventTypeDiscordSendFailed, source, payload)
if err != nil {
ctxLogger.Error(service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot create event [%s] for user with id [%s]", events.EventTypeDiscordSendFailed, payload.UserID)))
return
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
ctxLogger.Error(service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot dispatch event [%s] for user with id [%s]", event.Type(), payload.UserID)))
return
}
ctxLogger.Info(fmt.Sprintf("dispatched event [%s] for user with id [%s]", event.Type(), payload.UserID))
}
|