tsk-54: Tweak instant message endpoint to save contact and message identification (#56)

Closes #54

Reviewed-on: phoenix/textsender-api#56
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-12-22 22:39:29 +00:00
committed by phoenix
parent f5f753fe02
commit 6fa5ede358
10 changed files with 45 additions and 28 deletions
+1 -1
View File
@@ -5,5 +5,5 @@ import (
)
type App struct {
TwilioConfig *config.TwiloConfig
TwilioConfig *config.TwilioConfig
}
+12 -12
View File
@@ -14,11 +14,11 @@ import (
)
type Config struct {
DBConnString string
ServerPort string
ResetDB bool
JWTSecret string `env:"JWT_SECRET" required:"true"`
TwilioConfig *config.TwiloConfig
DBConnString string
ServerPort string
ResetDB bool
JWTSecret string `env:"JWT_SECRET" required:"true"`
TwilioConfig *config.TwilioConfig
AllowedOrigins []string
}
@@ -49,7 +49,7 @@ func PrintName() {
fmt.Println(version.String())
}
func Load() (*Config, *config.TwiloConfig, error) {
func Load() (*Config, *config.TwilioConfig, error) {
versionFlag := flag.Bool("version", false, "Print version information")
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
port := flag.String("port", PORT, "Server port")
@@ -72,10 +72,10 @@ func Load() (*Config, *config.TwiloConfig, error) {
} else {
allowedOrigins := unpackAllowedOrigins()
return &Config{
DBConnString: dbConnString,
ServerPort: *port,
ResetDB: *resetDb,
JWTSecret: os.Getenv("JWT_SECRET"),
DBConnString: dbConnString,
ServerPort: *port,
ResetDB: *resetDb,
JWTSecret: os.Getenv("JWT_SECRET"),
AllowedOrigins: allowedOrigins,
}, cfg, nil
}
@@ -138,7 +138,7 @@ func unpackAllowedOrigins() []string {
return allowedOriginsSplit
}
func TwilioConfig() (*config.TwiloConfig, error) {
func TwilioConfig() (*config.TwilioConfig, error) {
authSid := os.Getenv("TWILIO_AUTH_SID")
serviceSid := os.Getenv("TWILIO_SERVICE_SID")
authToken := os.Getenv("TWILIO_AUTH_TOKEN")
@@ -153,7 +153,7 @@ func TwilioConfig() (*config.TwiloConfig, error) {
} else if len(phoneNumber) == 0 {
return nil, fmt.Errorf("Twilio config phone number not found")
} else {
var cfg config.TwiloConfig
var cfg config.TwilioConfig
cfg.AccountSID = authSid
cfg.ServiceSID = serviceSid
cfg.AuthToken = authToken
+3 -3
View File
@@ -54,14 +54,14 @@ func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
}
defer r.Body.Close()
newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: req.UserId}
newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: &req.UserId}
var statusCode int
var resp AddContactResponse
ctx := r.Context()
if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, newContact.UserId); err != nil {
if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, *newContact.UserId); err != nil {
fmt.Printf("Error: %v", err)
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
@@ -157,7 +157,7 @@ func (c *ContactHandler) GetContact(w http.ResponseWriter, r *http.Request) {
fmt.Println("Checking with User Id")
if contacts, err := c.ContactStore.GetAllContacts(ctx); err == nil {
for _, con := range contacts {
if con.UserId == userId {
if *con.UserId == userId {
resp.Data = append(resp.Data, *con)
}
}
+3
View File
@@ -110,6 +110,9 @@ func (s *SendInstantMessageHandler) Send(w http.ResponseWriter, r *http.Request)
mer.Response = data
mer.UserId = req.UserId
mer.Sent = parsedTime
mer.Status = message.Message_Event_Response_Status_Instant
mer.ContactId = c.Id
mer.MessageId = &msg.Id
if err := s.MERStore.Create(ctx, &mer); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
@@ -26,6 +26,9 @@ type RecordEventRequest struct {
Response types.JSONB `json:"response"`
UserId uuid.UUID `json:"user_id"`
Sent *time.Time `json:"sent,omitempty"`
Status string `json:"status"`
ContactId *uuid.UUID `json:"contact_id"`
MessageId *uuid.UUID `json:"message_id"`
}
type RecordEventResponse struct {
@@ -62,6 +65,14 @@ func (e *EventResponseHandler) RecordResponse(w http.ResponseWriter, r *http.Req
rp.UserId = req.UserId
rp.Sent = *req.Sent
if req.Status == message.Message_Event_Response_Status_Instant {
rp.Status = req.Status
rp.MessageId = req.MessageId
rp.ContactId = req.ContactId
} else if req.Status == message.Message_Event_Response_Status_Scheduled {
rp.Status = req.Status
}
ctx := r.Context()
if err := e.MessageEventResponseStore.Create(ctx, &rp); err != nil {
resp.Message = err.Error()
@@ -60,7 +60,7 @@ func TestRecordMessageEventResponseWithMock(t *testing.T) {
sent := now.Add(30 * time.Minute)
bytes := []byte("{\"body\":\"Whoknows?\",\"num_segments\":\"0\",\"direction\":\"outbound-api\",\"from\":\"+12243026041\",\"to\":\"+16303831708\",\"date_updated\":\"Sat,29Nov202519:06:59+0000\",\"uri\":\"/2010-04-01/Accounts/ACefa1ef516314c9d1a68cbd657de49277/Messages/SM1193a529e7f7a840667cd1e0f13ea95a.json\",\"account_sid\":\"ACefa1ef516314c9d1a68cbd657de49277\",\"num_media\":\"0\",\"status\":\"scheduled\",\"messaging_service_sid\":\"MG803f3676706b92eb02e18dd820c447f2\",\"sid\":\"SM1193a529e7f7a840667cd1e0f13ea95a\",\"date_created\":\"Sat,29Nov202519:06:59+0000\",\"api_version\":\"2010-04-01\",\"subresource_uris\":{\"media\":\"/2010-04-01/Accounts/ACefa1ef516314c9d1a68cbd657de49277/Messages/SM1193a529e7f7a840667cd1e0f13ea95a/Media.json\"}}")
testReq := RecordEventRequest{ScheduledMessageEventId: event.Id, Response: bytes, UserId: schMsg.UserId, Sent: &sent}
testReq := RecordEventRequest{ScheduledMessageEventId: event.Id, Response: bytes, UserId: schMsg.UserId, Sent: &sent, Status: message.Message_Event_Response_Status_Scheduled}
jsonValue, _ := json.Marshal(testReq)
req, _ := http.NewRequest("POST", endpoint.RecordEventResponse, strings.NewReader(string(jsonValue)))
@@ -27,10 +27,10 @@ func (m *PGMessageEventResponseStore) Create(ctx context.Context, mer *message.M
queryReturn := "RETURNING id"
if mer.ScheduledMessageEventId == uuid.Nil {
query = fmt.Sprintf("%s (response, user_id, sent) VALUES ($1, $2, $3) %s", queryBase, queryReturn)
return m.db.QueryRow(ctx, query, mer.Response, mer.UserId, mer.Sent).Scan(&mer.Id)
query = fmt.Sprintf("%s (response, user_id, sent, contact_id, message_id) VALUES ($1, $2, $3, $4, $5) %s", queryBase, queryReturn)
return m.db.QueryRow(ctx, query, mer.Response, mer.UserId, mer.Sent, mer.ContactId, mer.MessageId).Scan(&mer.Id)
} else {
query = fmt.Sprintf("%s (scheduled_message_event_id, response, user_id, sent) %s", queryBase, queryReturn)
return m.db.QueryRow(ctx, query, mer.ScheduledMessageEventId, mer.Response, mer.UserId, mer.Sent).Scan(&mer.Id)
query = fmt.Sprintf("%s (scheduled_message_event_id, response, user_id, sent, contact_id, message_id) VALUES ($1, $2, $3, $4, $5, $6) %s", queryBase, queryReturn)
return m.db.QueryRow(ctx, query, mer.ScheduledMessageEventId, mer.Response, mer.UserId, mer.Sent, mer.ContactId, mer.MessageId).Scan(&mer.Id)
}
}