Skip to content

feat(presence): expose POST /message/subscribe to receive contact presence - #152

Open
nicolasnovis wants to merge 1 commit into
evolution-foundation:mainfrom
nicolasnovis:pr/subscribe-presence
Open

feat(presence): expose POST /message/subscribe to receive contact presence#152
nicolasnovis wants to merge 1 commit into
evolution-foundation:mainfrom
nicolasnovis:pr/subscribe-presence

Conversation

@nicolasnovis

@nicolasnovis nicolasnovis commented Jul 31, 2026

Copy link
Copy Markdown

Addresses part of #146 (the SubscribePresence half).

whatsmeow only delivers events.Presence (online/offline/last-seen) for JIDs you've explicitly SubscribePresence'd, and only while the instance is marked available. Today there is no route to subscribe, so the existing events.Presence handler never fires.

This adds POST /message/subscribe {number} which sends available first (idempotent — chat presence and the background presence loop already do this) and then calls client.SubscribePresence(jid). Subscriptions are ephemeral (reset on reconnect), so callers re-subscribe when a chat is opened.

It also enriches the Presence webhook payload with explicit top-level from and lastSeen (unix) fields, so consumers don't have to depend on types.JID / time.Time JSON marshaling.

Tested in production: opening a chat subscribes the contact, and online/offline/last-seen events flow through the webhook.

Summary by Sourcery

Add an endpoint and service support to subscribe to WhatsApp contact presence and enrich emitted presence webhooks.

New Features:

  • Expose POST /message/subscribe API to subscribe an instance to a contact's presence updates.
  • Introduce a SubscribePresence service struct and method to manage presence subscriptions for specific numbers.
  • Extend presence webhook payloads with explicit from and lastSeen fields for easier consumption.

Enhancements:

  • Wire the new subscribe presence handler into the routing layer with existing JID/number validation middleware.

Add POST /message/subscribe so an instance can subscribe to a contact's
WhatsApp presence. whatsmeow only delivers events.Presence for JIDs we've
explicitly subscribed to (and only while marked available), so the handler
sends available first, then SubscribePresence(jid). Subscriptions are
ephemeral, so callers re-subscribe when a chat is opened.

Also enrich the events.Presence webhook with explicit top-level 'from' and
'lastSeen' (unix) fields so consumers don't depend on JID/time marshaling.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds a new POST /message/subscribe endpoint and service method to explicitly subscribe an instance to a contact’s presence updates in WhatsApp (via whatsmeow), and enriches Presence webhook events with top-level from and lastSeen fields.

Sequence diagram for POST /message/subscribe presence subscription flow

sequenceDiagram
    actor ApiClient
    participant GinRouter
    participant MessageHandler
    participant MessageService
    participant MyClient

    ApiClient->>GinRouter: POST /message/subscribe {number}
    GinRouter->>MessageHandler: SubscribePresence(ctx)
    MessageHandler->>MessageHandler: ctx.MustGet(instance)
    MessageHandler->>MessageHandler: ctx.ShouldBindBodyWithJSON(data)
    MessageHandler->>MessageService: SubscribePresence(data, instance)
    MessageService->>MessageService: ensureClientConnected(instance.Id)
    MessageService->>MessageService: utils.ParseJID(data.Number)
    MessageService->>MessageService: utils.CanonicalJID(recipient)
    MessageService->>MyClient: SendPresence(ctx, types.PresenceAvailable)
    MessageService->>MyClient: SubscribePresence(ctx, recipient)
    MessageService-->>MessageHandler: nil
    MessageHandler-->>ApiClient: 200 {"message":"success"}
Loading

Sequence diagram for updated Presence webhook event enrichment

sequenceDiagram
    participant WhatsApp
    participant MyClient

    WhatsApp-->>MyClient: events.Presence evt
    MyClient->>MyClient: myEventHandler(evt)
    MyClient->>MyClient: postMap["event"] = "Presence"
    MyClient->>MyClient: postMap["from"] = evt.From.String()
    alt evt.Unavailable && !evt.LastSeen.IsZero()
        MyClient->>MyClient: postMap["state"] = "offline"
        MyClient->>MyClient: postMap["lastSeen"] = evt.LastSeen.Unix()
    else evt.Unavailable && evt.LastSeen.IsZero()
        MyClient->>MyClient: postMap["state"] = "offline"
    else !evt.Unavailable
        MyClient->>MyClient: postMap["state"] = "online"
    end
Loading

File-Level Changes

Change Details Files
Introduce HTTP handler and routing for subscribing to contact presence.
  • Extend MessageHandler interface with a SubscribePresence method.
  • Implement SubscribePresence handler that resolves the instance, validates request body (number required), delegates to messageService.SubscribePresence, and returns appropriate HTTP status codes.
  • Register POST /message/subscribe route under /message with existing JID validation middleware.
pkg/message/handler/message_handler.go
pkg/routes/routes.go
Add service-layer support for presence subscription using whatsmeow client.
  • Extend MessageService interface with SubscribePresence method and define SubscribePresenceStruct with a Number field.
  • Implement SubscribePresence to ensure a connected client, parse and canonicalize the target JID from the phone number, send PresenceAvailable (non-fatal if it fails), invoke client.SubscribePresence, and log success or errors.
  • Ensure errors for invalid phone numbers and subscribe failures are surfaced to the handler.
pkg/message/service/message_service.go
Enrich Presence webhook payloads with explicit metadata to simplify consumers.
  • In the whatsmeow event handler, for events.Presence, add top-level from (JID string) to the webhook payload.
  • When the presence is unavailable and LastSeen is non-zero, add a top-level lastSeen field as a Unix timestamp while preserving existing logging behavior.
pkg/whatsmeow/service/whatsmeow.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • In SubscribePresence handler you declare var data *message_service.SubscribePresenceStruct and pass &data to ShouldBindBodyWithJSON; this creates a pointer-to-pointer pattern that is unusual for Gin and inconsistent with the other handlers—consider using a value struct (e.g. var data message_service.SubscribePresenceStruct and binding into &data) for simpler and safer binding.
  • In MessageService.SubscribePresence you use context.Background() for SendPresence and SubscribePresence; consider threading through a request-scoped context (or a context with timeout) so these calls respect client cancellation and avoid potentially hanging operations.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `SubscribePresence` handler you declare `var data *message_service.SubscribePresenceStruct` and pass `&data` to `ShouldBindBodyWithJSON`; this creates a pointer-to-pointer pattern that is unusual for Gin and inconsistent with the other handlers—consider using a value struct (e.g. `var data message_service.SubscribePresenceStruct` and binding into `&data`) for simpler and safer binding.
- In `MessageService.SubscribePresence` you use `context.Background()` for `SendPresence` and `SubscribePresence`; consider threading through a request-scoped context (or a context with timeout) so these calls respect client cancellation and avoid potentially hanging operations.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant