GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix(user): tell "no avatar" apart from "hidden avatar" in GET /user/avatar (#859)
Aguinaldo Tupy341b15728f0a
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 41690b81..4064d53c 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -1026,6 +1026,34 @@ paths:application/json:schema:$ref: '#/components/schemas/ErrorBadRequest'+ '403':+ description: 'AVATAR_HIDDEN: the contact hides the picture from this account (says nothing about whether one exists)'+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorForbidden'+ example:+ code: AVATAR_HIDDEN+ message: the user has hidden their profile picture from you+ '404':+ description: 'The contact has no profile picture (AVATAR_NOT_SET) or the device is unknown (DEVICE_NOT_FOUND). Check `code`, not only the status.'+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorNotFound'+ examples:+ avatarNotSet:+ summary: The contact has no profile picture+ value:+ code: AVATAR_NOT_SET+ message: that user or group does not have a profile picture+ deviceNotFound:+ summary: Unknown device+ value:+ code: DEVICE_NOT_FOUND+ message: device not found; create a device first from /api/devices or provide a valid X-Device-Id+ results:+ device_id: my-device'500':description: Internal Server Errorcontent:@@ -5511,6 +5539,20 @@ components:type: objectexample: nulldescription: 'additional data'+ ErrorForbidden:+ type: object+ properties:+ code:+ type: string+ example: AVATAR_HIDDEN+ description: 'SYSTEM_CODE_ERROR'+ message:+ type: string+ example: the user has hidden their profile picture from you+ description: 'Detail error message'+ results:+ type: object+ description: 'additional data'ErrorNotFound:type: objectproperties:diff --git a/src/pkg/error/whatsapp_error.go b/src/pkg/error/whatsapp_error.goindex e9f8c7fa..73684678 100644--- a/src/pkg/error/whatsapp_error.go+++ b/src/pkg/error/whatsapp_error.go@@ -87,6 +87,45 @@ func (e WaReachoutTimelockError) StatusCode() int {return http.StatusTooManyRequests}+// AvatarNotSetError means the contact has no profile picture. It is a+// confirmed absence, distinct from AvatarHiddenError: clients that cache+// avatars may delete their copy on this one and must keep it on the other.+type AvatarNotSetError string++// Error for complying the error interface+func (e AvatarNotSetError) Error() string {+ return string(e)+}++// ErrCode will return the error code based on the error data type+func (e AvatarNotSetError) ErrCode() string {+ return "AVATAR_NOT_SET"+}++// StatusCode will return the HTTP status code based on the error data type+func (e AvatarNotSetError) StatusCode() int {+ return http.StatusNotFound+}++// AvatarHiddenError means the contact's privacy settings hide the picture+// from this account. It says nothing about whether a picture exists.+type AvatarHiddenError string++// Error for complying the error interface+func (e AvatarHiddenError) Error() string {+ return string(e)+}++// ErrCode will return the error code based on the error data type+func (e AvatarHiddenError) ErrCode() string {+ return "AVATAR_HIDDEN"+}++// StatusCode will return the HTTP status code based on the error data type+func (e AvatarHiddenError) StatusCode() int {+ return http.StatusForbidden+}+const (ErrUserNotRegistered = InvalidJID("user is not registered")ErrWaCLI = WaCliError("your WhatsApp CLI is invalid or empty")diff --git a/src/usecase/user.go b/src/usecase/user.goindex 1e3bd0df..ce29c713 100644--- a/src/usecase/user.go+++ b/src/usecase/user.go@@ -25,7 +25,9 @@ import ()type serviceUser struct {- chatStorageRepo domainChatStorage.IChatStorageRepository+ chatStorageRepo domainChatStorage.IChatStorageRepository+ validateJIDFn func(client *whatsmeow.Client, phone string) (types.JID, error)+ getProfilePictureInfoFn func(ctx context.Context, client *whatsmeow.Client, jid types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error)}func NewUserService(chatStorageRepo domainChatStorage.IChatStorageRepository) domainUser.IUserUsecase {@@ -34,6 +36,20 @@ func NewUserService(chatStorageRepo domainChatStorage.IChatStorageRepository) do}}+func (service serviceUser) validateJID(client *whatsmeow.Client, phone string) (types.JID, error) {+ if service.validateJIDFn != nil {+ return service.validateJIDFn(client, phone)+ }+ return utils.ValidateJidWithLogin(client, phone)+}++func (service serviceUser) getProfilePictureInfo(ctx context.Context, client *whatsmeow.Client, jid types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ if service.getProfilePictureInfoFn != nil {+ return service.getProfilePictureInfoFn(ctx, client, jid, params)+ }+ return client.GetProfilePictureInfo(ctx, jid, params)+}+func (service serviceUser) Info(ctx context.Context, request domainUser.InfoRequest) (response domainUser.InfoResponse, err error) {err = validations.ValidateUserInfo(ctx, request)if err != nil {@@ -133,7 +149,7 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.Avatarreturn response, err}- dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)+ dataWaRecipient, err := service.validateJID(client, request.Phone)if err != nil {return response, err}@@ -148,7 +164,7 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.AvataravatarCtx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()- pic, err := client.GetProfilePictureInfo(avatarCtx, dataWaRecipient, &whatsmeow.GetProfilePictureParams{+ pic, err := service.getProfilePictureInfo(avatarCtx, client, dataWaRecipient, &whatsmeow.GetProfilePictureParams{Preview: request.IsPreview,IsCommunity: isCommunity,})@@ -161,21 +177,40 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.AvataravatarCtx2, cancel2 := context.WithTimeout(ctx, 5*time.Second)defer cancel2()- pic, err = client.GetProfilePictureInfo(avatarCtx2, dataWaRecipient, &whatsmeow.GetProfilePictureParams{+ fallbackPic, fallbackErr := service.getProfilePictureInfo(avatarCtx2, client, dataWaRecipient, &whatsmeow.GetProfilePictureParams{Preview: request.IsPreview,IsCommunity: false,})- if err != nil {+ if fallbackErr != nil {if avatarCtx2.Err() == context.DeadlineExceeded {return response, pkgError.ContextError("Error timeout get avatar!")}- return response, err+ // In whatsmeow, GetProfilePictureInfo notes that community photos should use+ // IsCommunity: true, and that querying them with IsCommunity: false may return+ // 401 (ErrProfilePictureUnauthorized). Passing that fallback error directly+ // through avatarError would expose false-positive 403 AVATAR_HIDDEN signals.+ //+ // To keep AVATAR_HIDDEN and AVATAR_NOT_SET authoritative for caching clients,+ // only classify when both attempts agree on the sentinel. Otherwise, return+ // the fallback error unclassified.+ if errors.Is(err, whatsmeow.ErrProfilePictureNotSet) && errors.Is(fallbackErr, whatsmeow.ErrProfilePictureNotSet) {+ return response, avatarError(fallbackErr)+ }+ if errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) && errors.Is(fallbackErr, whatsmeow.ErrProfilePictureUnauthorized) {+ return response, avatarError(fallbackErr)+ }+ return response, fallbackErr}+ pic = fallbackPic} else {- return response, err+ return response, avatarError(err)}}+ // A nil picture without an error means "unchanged" (status 304 for a known+ // ExistingID), not "no picture": that one arrives as ErrProfilePictureNotSet+ // and is typed by avatarError. Keep it out of AvatarNotSetError so that+ // caching clients never drop a valid picture.if pic == nil {return response, errors.New("no avatar found")}@@ -511,3 +546,19 @@ func (service serviceUser) BusinessProfile(ctx context.Context, request domainUsreturn response, nil}++// avatarError types the two whatsmeow outcomes that clients must tell apart.+// Both used to surface as the same 500, and a client that cached avatars could+// only guess from the message text whether the picture was gone or merely+// hidden from this account. The messages are kept verbatim so that clients+// matching on text keep working.+func avatarError(err error) error {+ switch {+ case errors.Is(err, whatsmeow.ErrProfilePictureNotSet):+ return pkgError.AvatarNotSetError(err.Error())+ case errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized):+ return pkgError.AvatarHiddenError(err.Error())+ default:+ return err+ }+}diff --git a/src/usecase/user_test.go b/src/usecase/user_test.goindex 114b38c7..7deb0e68 100644--- a/src/usecase/user_test.go+++ b/src/usecase/user_test.go@@ -2,12 +2,20 @@ package usecaseimport ("bytes"+ "context"+ "errors"+ "fmt""image""image/png"+ "net/http""testing"+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/types")@@ -61,3 +69,277 @@ func TestContactDisplayName(t *testing.T) {})}}++func TestAvatarErrorTypesTheTwoOutcomesClientsMustTellApart(t *testing.T) {+ tests := []struct {+ name string+ err error+ wantCode string+ wantStatus int+ }{+ {name: "no picture", err: fmt.Errorf("wrapped: %w", whatsmeow.ErrProfilePictureNotSet), wantCode: "AVATAR_NOT_SET", wantStatus: http.StatusNotFound},+ {name: "hidden by privacy", err: fmt.Errorf("wrapped: %w", whatsmeow.ErrProfilePictureUnauthorized), wantCode: "AVATAR_HIDDEN", wantStatus: http.StatusForbidden},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, ok := avatarError(tt.err).(pkgError.GenericError)+ if !ok {+ t.Fatalf("avatarError(%v) is not a GenericError", tt.err)+ }+ if got.ErrCode() != tt.wantCode || got.StatusCode() != tt.wantStatus {+ t.Fatalf("got %s/%d, want %s/%d", got.ErrCode(), got.StatusCode(), tt.wantCode, tt.wantStatus)+ }+ // Clients matching on the message text keep working.+ if got.Error() != tt.err.Error() {+ t.Fatalf("message changed: %q, want %q", got.Error(), tt.err.Error())+ }+ })+ }++ other := errors.New("websocket not connected")+ if avatarError(other) != other {+ t.Fatalf("unrelated errors must pass through unchanged")+ }+}++func fakeAvatarContext() context.Context {+ client := &whatsmeow.Client{}+ instance := whatsapp.NewDeviceInstance("device-test", client, nil)+ return whatsapp.ContextWithDevice(context.Background(), instance)+}++func TestAvatarDirectLookup(t *testing.T) {+ ctx := fakeAvatarContext()++ tests := []struct {+ name string+ lookupErr error+ wantCode string+ wantStatus int+ rawErr bool+ }{+ {+ name: "wrapped ErrProfilePictureNotSet returns 404 AVATAR_NOT_SET",+ lookupErr: fmt.Errorf("lookup failed: %w", whatsmeow.ErrProfilePictureNotSet),+ wantCode: "AVATAR_NOT_SET",+ wantStatus: http.StatusNotFound,+ },+ {+ name: "wrapped ErrProfilePictureUnauthorized returns 403 AVATAR_HIDDEN",+ lookupErr: fmt.Errorf("lookup failed: %w", whatsmeow.ErrProfilePictureUnauthorized),+ wantCode: "AVATAR_HIDDEN",+ wantStatus: http.StatusForbidden,+ },+ {+ name: "unrelated lookup error passes through unclassified",+ lookupErr: errors.New("connection reset by peer"),+ rawErr: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, phone string) (types.JID, error) {+ return types.NewJID(phone, types.DefaultUserServer), nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ if params.IsCommunity {+ t.Fatal("expected IsCommunity=false for non-community lookup")+ }+ return nil, tt.lookupErr+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "628123456789"})+ if err == nil {+ t.Fatal("expected error, got nil")+ }++ if tt.rawErr {+ if _, ok := err.(pkgError.GenericError); ok {+ t.Fatalf("expected unclassified error, got GenericError: %v", err)+ }+ if !errors.Is(err, tt.lookupErr) {+ t.Fatalf("got %v, want %v", err, tt.lookupErr)+ }+ return+ }++ genericErr, ok := err.(pkgError.GenericError)+ if !ok {+ t.Fatalf("expected GenericError, got %T: %v", err, err)+ }+ if genericErr.ErrCode() != tt.wantCode || genericErr.StatusCode() != tt.wantStatus {+ t.Fatalf("got %s/%d, want %s/%d", genericErr.ErrCode(), genericErr.StatusCode(), tt.wantCode, tt.wantStatus)+ }+ })+ }+}++func TestAvatarCommunityFallback(t *testing.T) {+ ctx := fakeAvatarContext()+ groupJID := types.NewJID("[email protected]", types.GroupServer)++ t.Run("both attempts agree on ErrProfilePictureNotSet returns 404 AVATAR_NOT_SET", func(t *testing.T) {+ var calls []bool+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return groupJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ return nil, whatsmeow.ErrProfilePictureNotSet+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "[email protected]", IsCommunity: true})+ if len(calls) != 2 || calls[0] != true || calls[1] != false {+ t.Fatalf("expected [true, false] calls, got %v", calls)+ }+ genericErr, ok := err.(pkgError.GenericError)+ if !ok {+ t.Fatalf("expected GenericError, got %T: %v", err, err)+ }+ if genericErr.ErrCode() != "AVATAR_NOT_SET" || genericErr.StatusCode() != http.StatusNotFound {+ t.Fatalf("got %s/%d, want AVATAR_NOT_SET/404", genericErr.ErrCode(), genericErr.StatusCode())+ }+ })++ t.Run("both attempts agree on ErrProfilePictureUnauthorized returns 403 AVATAR_HIDDEN", func(t *testing.T) {+ var calls []bool+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return groupJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ return nil, whatsmeow.ErrProfilePictureUnauthorized+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "[email protected]", IsCommunity: true})+ if len(calls) != 2 || calls[0] != true || calls[1] != false {+ t.Fatalf("expected [true, false] calls, got %v", calls)+ }+ genericErr, ok := err.(pkgError.GenericError)+ if !ok {+ t.Fatalf("expected GenericError, got %T: %v", err, err)+ }+ if genericErr.ErrCode() != "AVATAR_HIDDEN" || genericErr.StatusCode() != http.StatusForbidden {+ t.Fatalf("got %s/%d, want AVATAR_HIDDEN/403", genericErr.ErrCode(), genericErr.StatusCode())+ }+ })++ t.Run("fallback ErrProfilePictureUnauthorized mismatch does not misclassify as AVATAR_HIDDEN", func(t *testing.T) {+ // When initial community query returns ErrProfilePictureNotSet, the fallback with+ // IsCommunity=false may trigger a 401 (ErrProfilePictureUnauthorized) from WhatsApp+ // simply because the JID is a community. This must NOT be exposed as 403 AVATAR_HIDDEN.+ var calls []bool+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return groupJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ if params.IsCommunity {+ return nil, whatsmeow.ErrProfilePictureNotSet+ }+ return nil, whatsmeow.ErrProfilePictureUnauthorized+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "[email protected]", IsCommunity: true})+ if len(calls) != 2 || calls[0] != true || calls[1] != false {+ t.Fatalf("expected [true, false] calls, got %v", calls)+ }+ if _, ok := err.(pkgError.GenericError); ok {+ t.Fatalf("expected unclassified error to prevent false cache signals, got GenericError: %v", err)+ }+ if !errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) {+ t.Fatalf("expected raw fallback error, got %v", err)+ }+ })++ t.Run("fallback query mode error does not misclassify when initial query had generic error", func(t *testing.T) {+ var calls []bool+ initialErr := errors.New("upstream timeout")+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return groupJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ if params.IsCommunity {+ return nil, initialErr+ }+ return nil, whatsmeow.ErrProfilePictureUnauthorized+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "[email protected]", IsCommunity: true})+ if len(calls) != 2 || calls[0] != true || calls[1] != false {+ t.Fatalf("expected [true, false] calls, got %v", calls)+ }+ if _, ok := err.(pkgError.GenericError); ok {+ t.Fatalf("expected unclassified error, got GenericError: %v", err)+ }+ if !errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) {+ t.Fatalf("expected raw fallback error, got %v", err)+ }+ })++ t.Run("fallback succeeds and returns picture URL", func(t *testing.T) {+ var calls []bool+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return groupJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ if params.IsCommunity {+ return nil, whatsmeow.ErrProfilePictureNotSet+ }+ return &types.ProfilePictureInfo{URL: "https://example.com/pic.jpg", ID: "pic-123", Type: "image"}, nil+ },+ }++ resp, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "[email protected]", IsCommunity: true})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(calls) != 2 || calls[0] != true || calls[1] != false {+ t.Fatalf("expected [true, false] calls, got %v", calls)+ }+ if resp.URL != "https://example.com/pic.jpg" || resp.ID != "pic-123" {+ t.Fatalf("unexpected response: %+v", resp)+ }+ })++ t.Run("regular user JID forces IsCommunity to false and skips fallback", func(t *testing.T) {+ var calls []bool+ userJID := types.NewJID("628123456789", types.DefaultUserServer)+ svc := serviceUser{+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {+ return userJID, nil+ },+ getProfilePictureInfoFn: func(_ context.Context, _ *whatsmeow.Client, _ types.JID, params *whatsmeow.GetProfilePictureParams) (*types.ProfilePictureInfo, error) {+ calls = append(calls, params.IsCommunity)+ return nil, whatsmeow.ErrProfilePictureNotSet+ },+ }++ _, err := svc.Avatar(ctx, domainUser.AvatarRequest{Phone: "628123456789", IsCommunity: true})+ if len(calls) != 1 || calls[0] != false {+ t.Fatalf("expected single call with IsCommunity=false, got %v", calls)+ }+ genericErr, ok := err.(pkgError.GenericError)+ if !ok {+ t.Fatalf("expected GenericError, got %T: %v", err, err)+ }+ if genericErr.ErrCode() != "AVATAR_NOT_SET" || genericErr.StatusCode() != http.StatusNotFound {+ t.Fatalf("got %s/%d, want AVATAR_NOT_SET/404", genericErr.ErrCode(), genericErr.StatusCode())+ }+ })+}