| 23 | var ErrInvalidNotificationType = errors.New("invalid notification type") |
| 24 | |
| 25 | func ProcessNotifications(sc smtp.SmtpClient) func(context.Context, *asynq.Task) error { |
| 26 | return func(ctx context.Context, t *asynq.Task) error { |
| 27 | n := ¬ification.Notification{} |
| 28 | err := msgpack.DecodeMsgPack(t.Payload(), &n) |
| 29 | if err != nil { |
| 30 | err := json.Unmarshal(t.Payload(), &n) |
| 31 | if err != nil { |
| 32 | // If unmarshal fails, try parsing as raw email.Message (backward compatibility) |
| 33 | np := &email.Message{} |
| 34 | err := msgpack.DecodeMsgPack(t.Payload(), np) |
| 35 | if err != nil { |
| 36 | err := json.Unmarshal(t.Payload(), np) |
| 37 | if err != nil { |
| 38 | return ErrInvalidNotificationPayload |
| 39 | } |
| 40 | } |
| 41 | // Successfully parsed as email, process it |
| 42 | if np.Email != "" { |
| 43 | newEmail := email.NewEmail(sc) |
| 44 | err = newEmail.Build(string(np.TemplateName), np.Params) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | return newEmail.Send(np.Email, np.Subject) |
| 49 | } |
| 50 | return ErrInvalidNotificationPayload |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // If NotificationType is empty and Payload is nil/empty, try parsing original payload as raw email.Message |
| 55 | payloadEmpty := n.Payload == nil |
| 56 | if !payloadEmpty { |
| 57 | // Check if payload is an empty map/interface |
| 58 | if payloadMap, ok := n.Payload.(map[string]interface{}); ok && len(payloadMap) == 0 { |
| 59 | payloadEmpty = true |
| 60 | } |
| 61 | } |
| 62 | if n.NotificationType == "" && payloadEmpty { |
| 63 | np := &email.Message{} |
| 64 | err := msgpack.DecodeMsgPack(t.Payload(), np) |
| 65 | if err != nil { |
| 66 | err := json.Unmarshal(t.Payload(), np) |
| 67 | if err != nil { |
| 68 | return ErrInvalidNotificationPayload |
| 69 | } |
| 70 | } |
| 71 | // Successfully parsed as email, process it |
| 72 | if np.Email != "" { |
| 73 | newEmail := email.NewEmail(sc) |
| 74 | err = newEmail.Build(string(np.TemplateName), np.Params) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | return newEmail.Send(np.Email, np.Subject) |
| 79 | } |
| 80 | return ErrInvalidNotificationPayload |
| 81 | } |
| 82 | |