|
| 1 | +package service |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/nethesis/matrix2acrobits/logger" |
| 11 | + "github.com/nethesis/matrix2acrobits/models" |
| 12 | + "maunium.net/go/mautrix" |
| 13 | + "maunium.net/go/mautrix/event" |
| 14 | + "maunium.net/go/mautrix/id" |
| 15 | +) |
| 16 | + |
| 17 | +// authenticateAndMapUser validates user credentials via external auth and returns the mapped Matrix user ID. |
| 18 | +// It persists the returned mapping for future reference. |
| 19 | +func (s *MessageService) authenticateAndMapUser(ctx context.Context, username, password string) (id.UserID, error) { |
| 20 | + userName := strings.TrimSpace(username) |
| 21 | + if userName == "" { |
| 22 | + logger.Warn().Msg("authentication: empty username") |
| 23 | + return "", ErrAuthentication |
| 24 | + } |
| 25 | + if strings.TrimSpace(password) == "" { |
| 26 | + logger.Warn().Msg("authentication: missing password") |
| 27 | + return "", ErrAuthentication |
| 28 | + } |
| 29 | + |
| 30 | + mapReq, status, err := s.authClient.Validate(ctx, userName, strings.TrimSpace(password), s.homeserverHost) |
| 31 | + if err != nil { |
| 32 | + if status == http.StatusUnauthorized { |
| 33 | + logger.Warn().Str("username", userName).Msg("external auth failed: unauthorized") |
| 34 | + return "", ErrAuthentication |
| 35 | + } |
| 36 | + logger.Error().Err(err).Int("status", status).Msg("external auth request failed") |
| 37 | + return "", fmt.Errorf("external auth request failed: %w", err) |
| 38 | + } |
| 39 | + |
| 40 | + // Persist mapping returned by auth |
| 41 | + if _, err := s.SaveMapping(mapReq); err != nil { |
| 42 | + logger.Error().Err(err).Msg("failed to save mapping from external auth response") |
| 43 | + return "", fmt.Errorf("failed to save mapping: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + userID := id.UserID(strings.TrimSpace(mapReq.MatrixID)) |
| 47 | + if userID == "" { |
| 48 | + logger.Warn().Str("username", userName).Msg("auth returned empty Matrix user ID") |
| 49 | + return "", ErrAuthentication |
| 50 | + } |
| 51 | + |
| 52 | + return userID, nil |
| 53 | +} |
| 54 | + |
| 55 | +// performSyncWithRetry performs a sync and retries with a full sync if the batch token is invalid. |
| 56 | +// This handles the case where the stored sync token expires or becomes invalid. |
| 57 | +func (s *MessageService) performSyncWithRetry(ctx context.Context, userID id.UserID, batchToken string) (*mautrix.RespSync, error) { |
| 58 | + resp, err := s.matrixClient.Sync(ctx, userID, batchToken) |
| 59 | + if err != nil { |
| 60 | + // If the token is invalid, retry with a full sync |
| 61 | + if strings.Contains(err.Error(), "Invalid stream token") || strings.Contains(err.Error(), "M_UNKNOWN") { |
| 62 | + logger.Warn().Err(err).Msg("invalid stream token, retrying with full sync") |
| 63 | + s.clearBatchToken(string(userID)) |
| 64 | + resp, err = s.matrixClient.Sync(ctx, userID, "") |
| 65 | + } |
| 66 | + } |
| 67 | + if err != nil { |
| 68 | + logger.Error().Str("user_id", string(userID)).Err(err).Msg("matrix sync failed") |
| 69 | + return nil, fmt.Errorf("sync messages: %w", mapAuthErr(err)) |
| 70 | + } |
| 71 | + return resp, nil |
| 72 | +} |
| 73 | + |
| 74 | +// processSyncedMessages converts Matrix sync events to Acrobits SMS format. |
| 75 | +// It processes both received and sent messages, resolving Matrix IDs to phone numbers. |
| 76 | +func (s *MessageService) processSyncedMessages(ctx context.Context, resp *mautrix.RespSync, userID string) ([]models.SMS, []models.SMS) { |
| 77 | + received := make([]models.SMS, 0, 8) |
| 78 | + sent := make([]models.SMS, 0, 8) |
| 79 | + |
| 80 | + // Resolve the caller's identifier |
| 81 | + callerIdentifier := s.resolveMatrixIDToIdentifier(userID) |
| 82 | + |
| 83 | + for roomID, room := range resp.Rooms.Join { |
| 84 | + for _, evt := range room.Timeline.Events { |
| 85 | + if evt.Type != event.EventMessage { |
| 86 | + continue |
| 87 | + } |
| 88 | + |
| 89 | + sms := s.convertMatrixEventToSMS(ctx, evt, roomID) |
| 90 | + senderMatrixID := string(evt.Sender) |
| 91 | + |
| 92 | + // Determine if this message was sent by the user |
| 93 | + if isSentBy(senderMatrixID, userID) { |
| 94 | + // Message was sent by this user |
| 95 | + other := s.resolveRoomIDToOtherIdentifier(ctx, evt.RoomID, userID) |
| 96 | + sms.Recipient = other |
| 97 | + sent = append(sent, sms) |
| 98 | + logger.Debug(). |
| 99 | + Str("sender", sms.Sender). |
| 100 | + Str("recipient", sms.Recipient). |
| 101 | + Msg("processed sent message from sync") |
| 102 | + } else { |
| 103 | + // Message was received by this user |
| 104 | + sms.Recipient = callerIdentifier |
| 105 | + received = append(received, sms) |
| 106 | + logger.Debug(). |
| 107 | + Str("sender", sms.Sender). |
| 108 | + Str("recipient", sms.Recipient). |
| 109 | + Msg("processed received message from sync") |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + logger.Debug(). |
| 115 | + Int("received_count", len(received)). |
| 116 | + Int("sent_count", len(sent)). |
| 117 | + Msg("finished processing synced messages") |
| 118 | + |
| 119 | + return received, sent |
| 120 | +} |
| 121 | + |
| 122 | +// convertMatrixEventToSMS converts a Matrix message event to an Acrobits SMS format. |
| 123 | +// It extracts message metadata and resolves the sender to a phone number if available. |
| 124 | +func (s *MessageService) convertMatrixEventToSMS(ctx context.Context, evt *event.Event, roomID id.RoomID) models.SMS { |
| 125 | + eventRoomID := evt.RoomID |
| 126 | + if eventRoomID == "" { |
| 127 | + eventRoomID = roomID |
| 128 | + } |
| 129 | + |
| 130 | + body := "" |
| 131 | + if b, ok := evt.Content.Raw["body"].(string); ok { |
| 132 | + body = b |
| 133 | + } |
| 134 | + |
| 135 | + senderMatrixID := string(evt.Sender) |
| 136 | + logger.Debug(). |
| 137 | + Str("event_id", string(evt.ID)). |
| 138 | + Str("room_id", string(eventRoomID)). |
| 139 | + Str("sender", senderMatrixID). |
| 140 | + Msg("converting matrix event to SMS") |
| 141 | + |
| 142 | + return models.SMS{ |
| 143 | + SMSID: string(evt.ID), |
| 144 | + SendingDate: time.UnixMilli(evt.Timestamp).UTC().Format(time.RFC3339), |
| 145 | + SMSText: body, |
| 146 | + ContentType: "text/plain", |
| 147 | + StreamID: string(roomID), |
| 148 | + Sender: string(s.resolveMatrixIDToIdentifier(senderMatrixID)), |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +// updateBatchToken stores the next batch token from a sync response for incremental syncing. |
| 153 | +func (s *MessageService) updateBatchToken(userID string, nextBatch string) { |
| 154 | + if nextBatch != "" { |
| 155 | + s.setBatchToken(userID, nextBatch) |
| 156 | + logger.Debug().Str("user_id", userID).Str("next_batch", nextBatch).Msg("stored next batch token") |
| 157 | + } |
| 158 | +} |
0 commit comments