Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(message): add forward message by ID (#394) (#755)

Aldino Kemal276c8d752df8
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index b94063bc..43a844e5 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2145,6 +2145,64 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /message/{message_id}/forward:
+ post:
+ operationId: forwardMessage
+ tags:
+ - message
+ summary: Forward Message
+ description: |
+ Forward a message that exists in local chat storage to another chat by message ID.
+ Text and standard media types (image, video, video note, audio, document, sticker) are supported.
+ Media references are reused when possible; stale refs trigger an automatic re-upload fallback.
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ - in: path
+ name: message_id
+ schema:
+ type: string
+ required: true
+ description: Source message ID from chat storage
+ example: '3EB0123456789ABCDEF'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - phone
+ properties:
+ phone:
+ type: string
+ example: '[email protected]'
+ description: Destination phone number or group JID
+ duration:
+ type: integer
+ example: 0
+ description: Optional disappearing message duration override (0, 86400, 604800, 7776000)
+ force_reupload:
+ type: boolean
+ example: false
+ description: Skip media reference reuse and re-upload media before sending
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SendResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
/message/{message_id}/download:
get:
operationId: downloadMessageMedia
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 9ab5ecfa..4a619831 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -145,7 +145,7 @@ func restServer(_ *cobra.Command, _ []string) {
rest.InitRestChat(r, chatUsecase)
rest.InitRestSend(r, sendUsecase)
rest.InitRestUser(r, userUsecase)
- rest.InitRestMessage(r, messageUsecase)
+ rest.InitRestMessage(r, messageUsecase, sendUsecase)
rest.InitRestGroup(r, groupUsecase)
rest.InitRestNewsletter(r, newsletterUsecase)
websocket.RegisterRoutes(r, appUsecase)
diff --git a/src/domains/send/forward.go b/src/domains/send/forward.go
new file mode 100644
index 00000000..caa78538
--- /dev/null
+++ b/src/domains/send/forward.go
@@ -0,0 +1,8 @@
+package send
+
+type ForwardRequest struct {
+ MessageID string `json:"message_id" form:"message_id"`
+ Phone string `json:"phone" form:"phone"`
+ Duration *int `json:"duration,omitempty" form:"duration"`
+ ForceReupload bool `json:"force_reupload,omitempty" form:"force_reupload"`
+}
diff --git a/src/domains/send/interfaces.go b/src/domains/send/interfaces.go
index 69c1d5d1..8d4d92db 100644
--- a/src/domains/send/interfaces.go
+++ b/src/domains/send/interfaces.go
@@ -32,10 +32,16 @@ type IPresenceSender interface {
SendChatPresence(ctx context.Context, request ChatPresenceRequest) (response GenericResponse, err error)
}
+// IForwardSender handles forward-by-message-id operations
+type IForwardSender interface {
+ SendForward(ctx context.Context, request ForwardRequest) (response GenericResponse, err error)
+}
+
// ISendUsecase combines all sender interfaces for backward compatibility
type ISendUsecase interface {
ITextSender
IMediaSender
IInteractionSender
IPresenceSender
+ IForwardSender
}
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index 1e3904fd..c2c53eab 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -5,6 +5,7 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
+ "errors"
"fmt"
"mime"
"net/url"
@@ -22,6 +23,7 @@ import (
"google.golang.org/protobuf/proto"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"go.mau.fi/whatsmeow"
)
@@ -358,6 +360,261 @@ func ResolveMediaDirectPath(storedDirectPath, mediaURL string) string {
return ""
}
+// ErrUnsupportedForwardType is returned when a stored message cannot be rebuilt for forward-by-ID.
+const ErrUnsupportedForwardType = "unsupported message type for forward"
+
+// ForwardBuildOptions controls proto rebuild for forward-by-ID sends.
+type ForwardBuildOptions struct {
+ Duration *int
+ Upload *whatsmeow.UploadResponse
+ MimeType string
+}
+
+var forwardableMediaTypes = map[string]struct{}{
+ "image": {},
+ "video": {},
+ "video_note": {},
+ "audio": {},
+ "ptt": {},
+ "document": {},
+ "sticker": {},
+}
+
+// IsForwardableStorageMessage reports whether a stored row can be forwarded by ID.
+func IsForwardableStorageMessage(message *domainChatStorage.Message) bool {
+ if message == nil {
+ return false
+ }
+ if message.MediaType == "call" {
+ return false
+ }
+ if _, ok := forwardableMediaTypes[message.MediaType]; ok {
+ return true
+ }
+ if message.MediaType != "" {
+ return false
+ }
+ if strings.TrimSpace(message.Content) == "" {
+ return false
+ }
+ return !isUnsupportedTextForwardContent(message.Content)
+}
+
+func isUnsupportedTextForwardContent(content string) bool {
+ trimmed := strings.TrimSpace(content)
+ if strings.HasPrefix(trimmed, "Contact:") || strings.HasPrefix(trimmed, "Contacts:") {
+ return true
+ }
+ if strings.Contains(trimmed, "https://maps.google.com/?q=") {
+ return true
+ }
+ return false
+}
+
+// IsForwardMediaMessage reports whether the stored row represents forwardable media (not plain text).
+func IsForwardMediaMessage(message *domainChatStorage.Message) bool {
+ if message == nil {
+ return false
+ }
+ _, ok := forwardableMediaTypes[message.MediaType]
+ return ok
+}
+
+func newForwardContextInfo(duration *int) *waE2E.ContextInfo {
+ ci := &waE2E.ContextInfo{
+ IsForwarded: proto.Bool(true),
+ ForwardingScore: proto.Uint32(100),
+ }
+ if duration != nil && *duration > 0 {
+ ci.Expiration = proto.Uint32(uint32(*duration))
+ }
+ return ci
+}
+
+// defaultForwardMimeType returns a mime type for stored media whose original
+// mime type was not persisted. WhatsApp transcodes media to fixed formats, so
+// per-type defaults are accurate except for documents, which are derived from
+// the stored filename.
+func defaultForwardMimeType(message *domainChatStorage.Message) string {
+ switch message.MediaType {
+ case "image":
+ return "image/jpeg"
+ case "video", "video_note":
+ return "video/mp4"
+ case "ptt":
+ return "audio/ogg; codecs=opus"
+ case "audio":
+ return "audio/mpeg"
+ case "sticker":
+ return "image/webp"
+ case "document":
+ ext := strings.ToLower(filepath.Ext(message.Filename))
+ if mimeType, ok := knownDocumentMIMEByExtension[ext]; ok {
+ return mimeType
+ }
+ if mimeType := mime.TypeByExtension(ext); mimeType != "" {
+ return mimeType
+ }
+ return "application/octet-stream"
+ default:
+ return ""
+ }
+}
+
+// BuildForwardMessageFromStorage rebuilds a sendable WhatsApp proto from chat storage.
+func BuildForwardMessageFromStorage(message *domainChatStorage.Message, opts ForwardBuildOptions) (*waE2E.Message, error) {
+ if message == nil {
+ return nil, fmt.Errorf("message is nil")
+ }
+ if !IsForwardableStorageMessage(message) {
+ return nil, errors.New(ErrUnsupportedForwardType)
+ }
+
+ contextInfo := newForwardContextInfo(opts.Duration)
+
+ if message.MediaType == "" {
+ return &waE2E.Message{
+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{
+ Text: proto.String(message.Content),
+ ContextInfo: contextInfo,
+ },
+ }, nil
+ }
+
+ var (
+ mediaURL string
+ directPath string
+ mediaKey []byte
+ fileSHA256 []byte
+ fileEncSHA256 []byte
+ fileLength uint64
+ )
+
+ if opts.Upload != nil {
+ mediaURL = opts.Upload.URL
+ directPath = opts.Upload.DirectPath
+ mediaKey = opts.Upload.MediaKey
+ fileSHA256 = opts.Upload.FileSHA256
+ fileEncSHA256 = opts.Upload.FileEncSHA256
+ fileLength = opts.Upload.FileLength
+ } else {
+ mediaURL = message.URL
+ directPath = ResolveMediaDirectPath(message.DirectPath, message.URL)
+ mediaKey = message.MediaKey
+ fileSHA256 = message.FileSHA256
+ fileEncSHA256 = message.FileEncSHA256
+ fileLength = message.FileLength
+ if directPath == "" && mediaURL == "" {
+ return nil, fmt.Errorf("message %s has no media references", message.ID)
+ }
+ }
+
+ caption := message.Content
+ filename := message.Filename
+
+ mimeType := opts.MimeType
+ if mimeType == "" {
+ mimeType = defaultForwardMimeType(message)
+ }
+
+ switch message.MediaType {
+ case "image":
+ img := &waE2E.ImageMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ Caption: proto.String(caption),
+ ContextInfo: contextInfo,
+ }
+ if mimeType != "" {
+ img.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{ImageMessage: img}, nil
+ case "video":
+ vid := &waE2E.VideoMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ Caption: proto.String(caption),
+ ContextInfo: contextInfo,
+ }
+ if mimeType != "" {
+ vid.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{VideoMessage: vid}, nil
+ case "video_note":
+ ptv := &waE2E.VideoMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ Caption: proto.String(caption),
+ ContextInfo: contextInfo,
+ }
+ if mimeType != "" {
+ ptv.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{PtvMessage: ptv}, nil
+ case "audio", "ptt":
+ aud := &waE2E.AudioMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ ContextInfo: contextInfo,
+ }
+ if message.MediaType == "ptt" {
+ aud.PTT = proto.Bool(true)
+ }
+ if mimeType != "" {
+ aud.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{AudioMessage: aud}, nil
+ case "document":
+ doc := &waE2E.DocumentMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ FileName: proto.String(filename),
+ Caption: proto.String(caption),
+ ContextInfo: contextInfo,
+ }
+ if mimeType != "" {
+ doc.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{DocumentMessage: doc}, nil
+ case "sticker":
+ sticker := &waE2E.StickerMessage{
+ URL: proto.String(mediaURL),
+ DirectPath: proto.String(directPath),
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: proto.Uint64(fileLength),
+ ContextInfo: contextInfo,
+ }
+ if mimeType != "" {
+ sticker.Mimetype = proto.String(mimeType)
+ }
+ return &waE2E.Message{StickerMessage: sticker}, nil
+ default:
+ return nil, errors.New(ErrUnsupportedForwardType)
+ }
+}
+
// BuildDownloadableMessage reconstructs a whatsmeow downloadable media proto
// from stored chat media metadata.
func BuildDownloadableMessage(mediaType, mediaURL, directPath, filename string, mediaKey, fileSHA256, fileEncSHA256 []byte, fileLength uint64) (whatsmeow.DownloadableMessage, error) {
diff --git a/src/pkg/utils/whatsapp_test.go b/src/pkg/utils/whatsapp_test.go
index c18e1a88..99d4acf6 100644
--- a/src/pkg/utils/whatsapp_test.go
+++ b/src/pkg/utils/whatsapp_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"testing"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"go.mau.fi/whatsmeow/proto/waE2E"
"google.golang.org/protobuf/proto"
)
@@ -597,3 +598,129 @@ func TestExtractMessageTextFromProtoExtendedTextMessage(t *testing.T) {
func strPtr(value string) *string {
return &value
}
+
+func TestBuildForwardMessageFromStorageText(t *testing.T) {
+ msg, err := BuildForwardMessageFromStorage(&domainChatStorage.Message{
+ Content: "hello forward",
+ }, ForwardBuildOptions{})
+ if err != nil {
+ t.Fatalf("BuildForwardMessageFromStorage() error = %v", err)
+ }
+ ext := msg.GetExtendedTextMessage()
+ if ext == nil {
+ t.Fatal("expected ExtendedTextMessage")
+ }
+ if ext.GetText() != "hello forward" {
+ t.Fatalf("text = %q, want %q", ext.GetText(), "hello forward")
+ }
+ if !ext.GetContextInfo().GetIsForwarded() {
+ t.Fatal("expected IsForwarded=true")
+ }
+ if ext.GetContextInfo().GetForwardingScore() != 100 {
+ t.Fatalf("forwarding score = %d, want 100", ext.GetContextInfo().GetForwardingScore())
+ }
+}
+
+func TestBuildForwardMessageFromStorageImage(t *testing.T) {
+ directPath := "/v/t62.media.enc"
+ msg, err := BuildForwardMessageFromStorage(&domainChatStorage.Message{
+ MediaType: "image",
+ Content: "caption text",
+ URL: "https://mmg.whatsapp.net/ignored",
+ DirectPath: directPath,
+ MediaKey: []byte("key"),
+ FileSHA256: []byte("sha"),
+ FileEncSHA256: []byte("enc"),
+ FileLength: 42,
+ }, ForwardBuildOptions{})
+ if err != nil {
+ t.Fatalf("BuildForwardMessageFromStorage() error = %v", err)
+ }
+ img := msg.GetImageMessage()
+ if img == nil {
+ t.Fatal("expected ImageMessage")
+ }
+ if img.GetCaption() != "caption text" {
+ t.Fatalf("caption = %q, want %q", img.GetCaption(), "caption text")
+ }
+ if img.GetDirectPath() != directPath {
+ t.Fatalf("directPath = %q, want %q", img.GetDirectPath(), directPath)
+ }
+ if !img.GetContextInfo().GetIsForwarded() {
+ t.Fatal("expected IsForwarded=true")
+ }
+ if img.GetMimetype() != "image/jpeg" {
+ t.Fatalf("mimetype = %q, want image/jpeg", img.GetMimetype())
+ }
+}
+
+func TestBuildForwardMessageFromStorageDocument(t *testing.T) {
+ msg, err := BuildForwardMessageFromStorage(&domainChatStorage.Message{
+ MediaType: "document",
+ Filename: "report.pdf",
+ Content: "see attached",
+ URL: "https://mmg.whatsapp.net/doc",
+ DirectPath: "/v/doc.enc",
+ MediaKey: []byte("key"),
+ FileSHA256: []byte("sha"),
+ FileEncSHA256: []byte("enc"),
+ FileLength: 100,
+ }, ForwardBuildOptions{})
+ if err != nil {
+ t.Fatalf("BuildForwardMessageFromStorage() error = %v", err)
+ }
+ doc := msg.GetDocumentMessage()
+ if doc == nil {
+ t.Fatal("expected DocumentMessage")
+ }
+ if doc.GetFileName() != "report.pdf" {
+ t.Fatalf("filename = %q, want report.pdf", doc.GetFileName())
+ }
+ if doc.GetCaption() != "see attached" {
+ t.Fatalf("caption = %q, want see attached", doc.GetCaption())
+ }
+ if doc.GetMimetype() != "application/pdf" {
+ t.Fatalf("mimetype = %q, want application/pdf", doc.GetMimetype())
+ }
+}
+
+func TestBuildForwardMessageFromStorageUnsupportedType(t *testing.T) {
+ _, err := BuildForwardMessageFromStorage(&domainChatStorage.Message{
+ MediaType: "call",
+ Content: "incoming call",
+ }, ForwardBuildOptions{})
+ if err == nil {
+ t.Fatal("expected error for call type")
+ }
+ if err.Error() != ErrUnsupportedForwardType {
+ t.Fatalf("error = %q, want %q", err.Error(), ErrUnsupportedForwardType)
+ }
+
+ _, err = BuildForwardMessageFromStorage(&domainChatStorage.Message{
+ Content: "Contact: Alice (+62 812)",
+ }, ForwardBuildOptions{})
+ if err == nil {
+ t.Fatal("expected error for contact summary")
+ }
+}
+
+func TestIsForwardableStorageMessage(t *testing.T) {
+ tests := []struct {
+ name string
+ message *domainChatStorage.Message
+ want bool
+ }{
+ {name: "text", message: &domainChatStorage.Message{Content: "hi"}, want: true},
+ {name: "image", message: &domainChatStorage.Message{MediaType: "image", URL: "u", DirectPath: "/p"}, want: true},
+ {name: "call", message: &domainChatStorage.Message{MediaType: "call"}, want: false},
+ {name: "contact", message: &domainChatStorage.Message{Content: "Contact: Bob"}, want: false},
+ {name: "location", message: &domainChatStorage.Message{Content: "Pin — https://maps.google.com/?q=1,2"}, want: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsForwardableStorageMessage(tt.message); got != tt.want {
+ t.Fatalf("IsForwardableStorageMessage() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/src/ui/mcp/send.go b/src/ui/mcp/send.go
index ac0616f3..b23222b0 100644
--- a/src/ui/mcp/send.go
+++ b/src/ui/mcp/send.go
@@ -32,6 +32,7 @@ func (s *SendHandler) AddSendTools(mcpServer *server.MCPServer) {
mcpServer.AddTool(s.toolSendDocument(), s.handleSendDocument)
mcpServer.AddTool(s.toolSendAudio(), s.handleSendAudio)
mcpServer.AddTool(s.toolSendPoll(), s.handleSendPoll)
+ mcpServer.AddTool(s.toolForwardMessage(), s.handleForwardMessage)
}
func (s *SendHandler) toolSendText() mcp.Tool {
@@ -663,3 +664,67 @@ func (s *SendHandler) handleSendPoll(ctx context.Context, request mcp.CallToolRe
return mcp.NewToolResultText(fmt.Sprintf("Poll sent successfully with ID %s", res.MessageID)), nil
}
+
+func (s *SendHandler) toolForwardMessage() mcp.Tool {
+ return mcp.NewTool("whatsapp_forward_message",
+ mcp.WithDescription("Forward an existing stored message to another chat by message ID. Reuses media references when possible."),
+ mcp.WithTitleAnnotation("Forward Message"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("message_id",
+ mcp.Required(),
+ mcp.Description("Source message ID from chat storage"),
+ ),
+ mcp.WithString("phone",
+ mcp.Required(),
+ mcp.Description("Destination phone number or group JID"),
+ ),
+ mcp.WithNumber("duration",
+ mcp.Description("Optional disappearing message duration in seconds (0, 86400, 604800, 7776000)"),
+ ),
+ mcp.WithBoolean("force_reupload",
+ mcp.Description("Skip media reference reuse and re-upload media before sending (default: false)"),
+ ),
+ )
+}
+
+func (s *SendHandler) handleForwardMessage(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ctx, err := mcpHelpers.ContextWithDefaultDevice(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ messageID, err := request.RequireString("message_id")
+ if err != nil {
+ return nil, err
+ }
+
+ phone, err := request.RequireString("phone")
+ if err != nil {
+ return nil, err
+ }
+
+ forwardRequest := domainSend.ForwardRequest{
+ MessageID: messageID,
+ Phone: phone,
+ ForceReupload: request.GetBool("force_reupload", false),
+ }
+
+ if args := request.GetArguments(); args != nil {
+ if _, ok := args["duration"]; ok {
+ duration, err := request.RequireInt("duration")
+ if err != nil {
+ return nil, err
+ }
+ forwardRequest.Duration = &duration
+ }
+ }
+
+ res, err := s.sendService.SendForward(ctx, forwardRequest)
+ if err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Message forwarded successfully with ID %s", res.MessageID)), nil
+}
diff --git a/src/ui/rest/message.go b/src/ui/rest/message.go
index e1ff0213..26f6ee37 100644
--- a/src/ui/rest/message.go
+++ b/src/ui/rest/message.go
@@ -8,17 +8,19 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
type Message struct {
- Service domainMessage.IMessageUsecase
+ Service domainMessage.IMessageUsecase
+ SendService domainSend.ISendUsecase
}
-func InitRestMessage(app fiber.Router, service domainMessage.IMessageUsecase) Message {
- rest := Message{Service: service}
+func InitRestMessage(app fiber.Router, service domainMessage.IMessageUsecase, sendService domainSend.ISendUsecase) Message {
+ rest := Message{Service: service, SendService: sendService}
// Message action endpoints
app.Post("/message/:message_id/reaction", rest.ReactMessage)
@@ -28,6 +30,7 @@ func InitRestMessage(app fiber.Router, service domainMessage.IMessageUsecase) Me
app.Post("/message/:message_id/read", rest.MarkAsRead)
app.Post("/message/:message_id/star", rest.StarMessage)
app.Post("/message/:message_id/unstar", rest.UnstarMessage)
+ app.Post("/message/:message_id/forward", rest.ForwardMessage)
app.Get("/message/:message_id/download", rest.DownloadMedia)
return rest
}
@@ -166,6 +169,25 @@ func (controller *Message) UnstarMessage(c *fiber.Ctx) error {
})
}
+func (controller *Message) ForwardMessage(c *fiber.Ctx) error {
+ var request domainSend.ForwardRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ request.MessageID = c.Params("message_id")
+ utils.SanitizePhone(&request.Phone)
+
+ response, err := controller.SendService.SendForward(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: response.Status,
+ Results: response,
+ })
+}
+
func (controller *Message) DownloadMedia(c *fiber.Ctx) error {
var request domainMessage.DownloadMediaRequest
diff --git a/src/usecase/forward.go b/src/usecase/forward.go
new file mode 100644
index 00000000..06735a52
--- /dev/null
+++ b/src/usecase/forward.go
@@ -0,0 +1,164 @@
+package usecase
+
+import (
+ "context"
+ "fmt"
+ "os"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "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/aldinokemal/go-whatsapp-web-multidevice/validations"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+)
+
+func (service serviceSend) SendForward(ctx context.Context, request domainSend.ForwardRequest) (response domainSend.GenericResponse, err error) {
+ if err = validations.ValidateForwardMessage(ctx, request); err != nil {
+ return response, err
+ }
+
+ message, err := service.chatStorageRepo.GetMessageByIDAndDevice(deviceIDFromContext(ctx), request.MessageID)
+ if err != nil {
+ return response, fmt.Errorf("failed to load message %s: %w", request.MessageID, err)
+ }
+ if message == nil {
+ return response, fmt.Errorf("message with ID %s not found", request.MessageID)
+ }
+
+ if !utils.IsForwardableStorageMessage(message) {
+ return response, pkgError.ValidationError(utils.ErrUnsupportedForwardType)
+ }
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
+ if err != nil {
+ return response, err
+ }
+
+ opts := utils.ForwardBuildOptions{Duration: forwardDurationOption(service, request)}
+ content := forwardStoredContent(message)
+
+ var msg *waE2E.Message
+ if request.ForceReupload && utils.IsForwardMediaMessage(message) {
+ msg, err = service.reuploadForwardMessage(ctx, client, message, dataWaRecipient, opts)
+ } else {
+ msg, err = utils.BuildForwardMessageFromStorage(message, opts)
+ }
+ if err != nil {
+ return response, err
+ }
+
+ ts, sendErr := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
+ if sendErr != nil && utils.IsForwardMediaMessage(message) && !request.ForceReupload {
+ reuploadMsg, reuploadErr := service.reuploadForwardMessage(ctx, client, message, dataWaRecipient, opts)
+ if reuploadErr != nil {
+ return response, sendErr
+ }
+ ts, sendErr = service.wrapSendMessage(ctx, client, dataWaRecipient, reuploadMsg, content)
+ }
+ if sendErr != nil {
+ return response, sendErr
+ }
+
+ response.MessageID = ts.ID
+ response.Status = fmt.Sprintf("Message forwarded to %s (server timestamp: %s)", request.Phone, ts.Timestamp.String())
+ return response, nil
+}
+
+func forwardDurationOption(service serviceSend, request domainSend.ForwardRequest) *int {
+ if request.Duration != nil {
+ return request.Duration
+ }
+ expiration := service.getDefaultEphemeralExpiration(request.Phone)
+ if expiration == 0 {
+ return nil
+ }
+ d := int(expiration)
+ return &d
+}
+
+func forwardStoredContent(message *domainChatStorage.Message) string {
+ if message.Content != "" {
+ return message.Content
+ }
+ switch message.MediaType {
+ case "image":
+ return "🖼️ Image"
+ case "video", "video_note":
+ return "🎬 Video"
+ case "audio", "ptt":
+ return "🎵 Audio"
+ case "document":
+ return "📄 Document"
+ case "sticker":
+ return "🎨 Sticker"
+ default:
+ return message.Content
+ }
+}
+
+func (service serviceSend) reuploadForwardMessage(ctx context.Context, client *whatsmeow.Client, message *domainChatStorage.Message, recipient types.JID, opts utils.ForwardBuildOptions) (*waE2E.Message, error) {
+ directPath := utils.ResolveMediaDirectPath(message.DirectPath, message.URL)
+ downloadable, err := utils.BuildDownloadableMessage(
+ message.MediaType,
+ message.URL,
+ directPath,
+ message.Filename,
+ message.MediaKey,
+ message.FileSHA256,
+ message.FileEncSHA256,
+ message.FileLength,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathSendItems, downloadable)
+ if err != nil {
+ return nil, fmt.Errorf("failed to download media for re-upload: %w", err)
+ }
+ defer os.Remove(extracted.MediaPath)
+
+ data, err := os.ReadFile(extracted.MediaPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read downloaded media: %w", err)
+ }
+
+ waMediaType, err := forwardWhatsmeowMediaType(message.MediaType)
+ if err != nil {
+ return nil, err
+ }
+
+ uploaded, err := service.uploadMedia(ctx, client, waMediaType, data, recipient)
+ if err != nil {
+ return nil, pkgError.WaUploadMediaError(fmt.Sprintf("failed to re-upload media: %v", err))
+ }
+
+ opts.Upload = &uploaded
+ opts.MimeType = extracted.MimeType
+ return utils.BuildForwardMessageFromStorage(message, opts)
+}
+
+func forwardWhatsmeowMediaType(mediaType string) (whatsmeow.MediaType, error) {
+ switch mediaType {
+ case "image", "sticker":
+ return whatsmeow.MediaImage, nil
+ case "video", "video_note":
+ return whatsmeow.MediaVideo, nil
+ case "audio", "ptt":
+ return whatsmeow.MediaAudio, nil
+ case "document":
+ return whatsmeow.MediaDocument, nil
+ default:
+ return "", fmt.Errorf("unsupported media type: %s", mediaType)
+ }
+}
diff --git a/src/usecase/send_test.go b/src/usecase/send_test.go
index f0f4229a..81c283fb 100644
--- a/src/usecase/send_test.go
+++ b/src/usecase/send_test.go
@@ -7,8 +7,10 @@ import (
"testing"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
"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"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waE2E"
"google.golang.org/protobuf/proto"
@@ -223,3 +225,61 @@ func TestMergeReplyContextLeavesExistingContextWhenReplyUnavailable(t *testing.T
})
}
}
+
+func TestSendForwardMessageNotFound(t *testing.T) {
+ repo := &replyMessageRepo{}
+ service := serviceSend{chatStorageRepo: repo}
+ deviceID := "[email protected]"
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))
+
+ _, err := service.SendForward(ctx, domainSend.ForwardRequest{
+ MessageID: "missing-id",
+ Phone: "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected error for missing message")
+ }
+ if repo.gotID != "missing-id" {
+ t.Fatalf("expected lookup for missing-id, got %q", repo.gotID)
+ }
+ if repo.gotDeviceID != deviceID {
+ t.Fatalf("expected device-scoped lookup for %q, got %q", deviceID, repo.gotDeviceID)
+ }
+}
+
+func TestForwardDurationOptionExplicitZero(t *testing.T) {
+ zero := 0
+ got := forwardDurationOption(serviceSend{}, domainSend.ForwardRequest{
+ Phone: "[email protected]",
+ Duration: &zero,
+ })
+ if got == nil || *got != 0 {
+ t.Fatalf("expected explicit duration 0 to be honored, got %v", got)
+ }
+}
+
+func TestSendForwardUnsupportedType(t *testing.T) {
+ repo := &replyMessageRepo{
+ message: &domainChatStorage.Message{
+ MediaType: "call",
+ Content: "incoming call",
+ },
+ }
+ service := serviceSend{chatStorageRepo: repo}
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance("[email protected]", nil, nil))
+
+ _, err := service.SendForward(ctx, domainSend.ForwardRequest{
+ MessageID: "call-msg-id",
+ Phone: "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected error for unsupported type")
+ }
+ genericErr, ok := err.(pkgError.GenericError)
+ if !ok {
+ t.Fatalf("expected validation error, got %T: %v", err, err)
+ }
+ if genericErr.Error() != utils.ErrUnsupportedForwardType {
+ t.Fatalf("error = %q, want %q", genericErr.Error(), utils.ErrUnsupportedForwardType)
+ }
+}
diff --git a/src/validations/send_validation.go b/src/validations/send_validation.go
index 09548f9f..4a625679 100644
--- a/src/validations/send_validation.go
+++ b/src/validations/send_validation.go
@@ -518,3 +518,24 @@ func ValidateSendChatPresence(ctx context.Context, request domainSend.ChatPresen
return nil
}
+
+func ValidateForwardMessage(ctx context.Context, request domainSend.ForwardRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.MessageID, validation.Required),
+ validation.Field(&request.Phone, validation.Required),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ if err := validatePhoneNumber(request.Phone); err != nil {
+ return err
+ }
+
+ if err := validateDuration(request.Duration); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/src/validations/send_validation_test.go b/src/validations/send_validation_test.go
index 35615a42..3dd2a764 100644
--- a/src/validations/send_validation_test.go
+++ b/src/validations/send_validation_test.go
@@ -1130,3 +1130,46 @@ func TestValidateSendAudio_WithDuration(t *testing.T) {
})
}
}
+
+func TestValidateForwardMessage(t *testing.T) {
+ type args struct {
+ request domainSend.ForwardRequest
+ }
+ tests := []struct {
+ name string
+ args args
+ err any
+ }{
+ {
+ name: "should success normal condition",
+ args: args{request: domainSend.ForwardRequest{
+ MessageID: "3EB0123456789ABCDEF",
+ Phone: "[email protected]",
+ }},
+ err: nil,
+ },
+ {
+ name: "should error with empty phone",
+ args: args{request: domainSend.ForwardRequest{
+ MessageID: "3EB0123456789ABCDEF",
+ Phone: "",
+ }},
+ err: pkgError.ValidationError("phone: cannot be blank."),
+ },
+ {
+ name: "should error with empty message id",
+ args: args{request: domainSend.ForwardRequest{
+ MessageID: "",
+ Phone: "[email protected]",
+ }},
+ err: pkgError.ValidationError("message_id: cannot be blank."),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateForwardMessage(context.Background(), tt.args.request)
+ assert.Equal(t, tt.err, err)
+ })
+ }
+}
diff --git a/src/views/components/SendForward.js b/src/views/components/SendForward.js
new file mode 100644
index 00000000..18eafc3a
--- /dev/null
+++ b/src/views/components/SendForward.js
@@ -0,0 +1,130 @@
+import FormRecipient from "./generic/FormRecipient.js";
+
+export default {
+ name: 'SendForward',
+ components: {
+ FormRecipient
+ },
+ data() {
+ return {
+ type: window.TYPEUSER,
+ phone: '',
+ message_id: '',
+ force_reupload: false,
+ duration: 0,
+ loading: false,
+ }
+ },
+ computed: {
+ phone_id() {
+ return this.phone + this.type;
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalSendForward').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
+ return false;
+ }
+ if (!this.message_id.trim()) {
+ return false;
+ }
+ return true;
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ const response = await this.submitApi();
+ showSuccessInfo(response);
+ $('#modalSendForward').modal('hide');
+ } catch (err) {
+ showErrorInfo(err);
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ const payload = {
+ phone: this.phone_id,
+ force_reupload: this.force_reupload,
+ };
+ if (this.duration && this.duration > 0) {
+ payload.duration = this.duration;
+ }
+ const response = await window.http.post(`/message/${this.message_id.trim()}/forward`, payload);
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response?.data?.message) {
+ throw new Error(error.response.data.message);
+ }
+ throw error;
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.phone = '';
+ this.message_id = '';
+ this.force_reupload = false;
+ this.duration = 0;
+ this.type = window.TYPEUSER;
+ },
+ },
+ template: `
+ <div class="red card" @click="openModal()" style="cursor: pointer">
+ <div class="content">
+ <a class="ui red right ribbon label">Message</a>
+ <div class="header">Forward Message</div>
+ <div class="description">
+ Forward a stored message to another chat by message ID
+ </div>
+ </div>
+ </div>
+
+ <div class="ui small modal" id="modalSendForward">
+ <i class="close icon"></i>
+ <div class="header">
+ Forward Message
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Source Message ID</label>
+ <input v-model="message_id" type="text"
+ placeholder="57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
+ aria-label="message id">
+ </div>
+ <FormRecipient v-model:type="type" v-model:phone="phone"/>
+ <div class="field">
+ <label>Force Re-upload</label>
+ <div class="ui toggle checkbox">
+ <input type="checkbox" aria-label="force reupload" v-model="force_reupload">
+ <label>Re-download and re-upload media instead of reusing CDN refs</label>
+ </div>
+ </div>
+ <div class="field">
+ <label>Disappearing Duration (seconds)</label>
+ <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': loading, 'disabled': !isValidForm() || loading}"
+ @click.prevent="handleSubmit">
+ Forward
+ <i class="share icon"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
diff --git a/src/views/index.html b/src/views/index.html
index 54f91bb7..c13c1265 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -110,6 +110,7 @@
<message-react></message-react>
<message-update></message-update>
<message-read></message-read>
+ <send-forward></send-forward>
</div>
<div class="ui horizontal divider">
@@ -231,6 +232,7 @@
import MessageReact from "{{ .AppBasePath }}/components/MessageReact.js";
import MessageRevoke from "{{ .AppBasePath }}/components/MessageRevoke.js";
import MessageRead from "{{ .AppBasePath }}/components/MessageRead.js";
+ import SendForward from "{{ .AppBasePath }}/components/SendForward.js";
import GroupList from "{{ .AppBasePath }}/components/GroupList.js";
import GroupCreate from "{{ .AppBasePath }}/components/GroupCreate.js";
import GroupJoinWithLink from "{{ .AppBasePath }}/components/GroupJoinWithLink.js";
@@ -282,7 +284,7 @@
components: {
AppLogin, AppLoginWithCode, AppLogout, AppReconnect,
SendMessage, SendImage, SendFile, SendVideo, SendSticker, SendLink, SendContact, SendLocation, SendAudio, SendPoll, SendPresence, SendChatPresence,
- MessageDelete, MessageUpdate, MessageReact, MessageRevoke, MessageRead,
+ MessageDelete, MessageUpdate, MessageReact, MessageRevoke, MessageRead, SendForward,
GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupGetInviteLink, GroupInfo,
NewsletterList,
AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,