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: Add chat list API with SQLite storage (#339)

Aldino Kemalb3fa65bdf694
diff --git a/.cursor/rules/project-structure.mdc b/.cursor/rules/project-structure.mdc
index 59276969..86df6c42 100644
--- a/.cursor/rules/project-structure.mdc
+++ b/.cursor/rules/project-structure.mdc
@@ -34,7 +34,7 @@ The main source code is organized in the `src` directory with the following stru
The application is organized using domain-driven design principles:
- [src/domains/app/](mdc:src/domains/app) - Core application domain models
-- [src/domains/device/](mdc:src/domains/device) - Device-related domain models
+- [src/domains/chat/](mdc:src/domains/chat) - Chat-related domain models and interfaces
- [src/domains/group/](mdc:src/domains/group) - Group-related domain models
- [src/domains/message/](mdc:src/domains/message) - Message-related domain models
- [src/domains/newsletter/](mdc:src/domains/newsletter) - Newsletter-related domain models
@@ -43,6 +43,7 @@ The application is organized using domain-driven design principles:
#### Infrastructure
+- [src/infrastructure/chatstorage/](mdc:src/infrastructure/chatstorage) - Chat storage repository and WhatsApp integration
- [src/infrastructure/whatsapp/](mdc:src/infrastructure/whatsapp) - WhatsApp client implementation and related infrastructure
#### User Interface
@@ -105,6 +106,7 @@ The application is organized using domain-driven design principles:
## Application Flow
### REST Server Mode
+
1. The application starts from [src/cmd/root.go](mdc:src/cmd/root.go)
2. REST server command is executed via [src/cmd/rest.go](mdc:src/cmd/rest.go)
3. Configuration is loaded from environment variables or command line flags
@@ -116,6 +118,7 @@ The application is organized using domain-driven design principles:
9. The server listens for requests on the configured port
### MCP Server Mode
+
1. The application starts from [src/cmd/root.go](mdc:src/cmd/root.go)
2. MCP server command is executed via [src/cmd/mcp.go](mdc:src/cmd/mcp.go)
3. Model Context Protocol server is initialized for AI agent communication
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index f0094830..c2e2408d 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 6.6.0
+ version: 6.7.0
description: This API is used for sending whatsapp via API
servers:
- url: http://localhost:3000
@@ -14,6 +14,8 @@ tags:
description: Send Message (Text/Image/File/Video).
- name: message
description: Message manipulation (revoke/react/update).
+ - name: chat
+ description: Chat conversations and messaging
- name: group
description: Group setting
- name: newsletter
@@ -1305,6 +1307,152 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+
+ /chats:
+ get:
+ operationId: listChats
+ tags:
+ - chat
+ summary: Get list of chats
+ description: Retrieve a list of chat conversations with their basic information
+ parameters:
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ default: 25
+ maximum: 100
+ description: Maximum number of chats to return
+ - name: offset
+ in: query
+ schema:
+ type: integer
+ default: 0
+ description: Number of chats to skip (for pagination)
+ - name: search
+ in: query
+ schema:
+ type: string
+ description: Search chats by name
+ - name: has_media
+ in: query
+ schema:
+ type: boolean
+ default: false
+ description: Filter chats that contain media messages
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ChatListResponse'
+ '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'
+ '401':
+ description: Unauthorized
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorUnauthorized'
+ /chat/{chat_jid}/messages:
+ get:
+ operationId: getChatMessages
+ tags:
+ - chat
+ summary: Get messages from a specific chat
+ description: Retrieve messages from a specific chat conversation with filtering options
+ parameters:
+ - in: path
+ name: chat_jid
+ schema:
+ type: string
+ required: true
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group)
+ example: '[email protected]'
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ default: 50
+ maximum: 100
+ description: Maximum number of messages to return
+ - name: offset
+ in: query
+ schema:
+ type: integer
+ default: 0
+ description: Number of messages to skip (for pagination)
+ - name: start_time
+ in: query
+ schema:
+ type: string
+ format: date-time
+ description: Filter messages from this timestamp (ISO 8601 format)
+ - name: end_time
+ in: query
+ schema:
+ type: string
+ format: date-time
+ description: Filter messages until this timestamp (ISO 8601 format)
+ - name: media_only
+ in: query
+ schema:
+ type: boolean
+ default: false
+ description: Only return messages with media content
+ - name: is_from_me
+ in: query
+ schema:
+ type: boolean
+ description: Filter messages by sender (true for messages sent by you, false for received messages). When both media_only=true and isFromMe=false are provided, media_only takes precedence and will return all media messages regardless of sender.
+ - name: search
+ in: query
+ schema:
+ type: string
+ description: Search messages by content text
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ChatMessagesResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '401':
+ description: Unauthorized
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorUnauthorized'
+ '404':
+ description: Chat Not Found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
/group:
post:
operationId: createGroup
@@ -2236,6 +2384,36 @@ components:
type: object
example: null
description: 'additional data'
+ ErrorUnauthorized:
+ type: object
+ properties:
+ code:
+ type: string
+ example: 401
+ description: 'HTTP Status Code'
+ message:
+ type: string
+ example: Unauthorized access
+ description: 'Detail error message'
+ results:
+ type: object
+ example: null
+ description: 'additional data'
+ ErrorNotFound:
+ type: object
+ properties:
+ code:
+ type: string
+ example: 404
+ description: 'HTTP Status Code'
+ message:
+ type: string
+ example: Chat not found
+ description: 'Detail error message'
+ results:
+ type: object
+ example: null
+ description: 'additional data'
NewsletterResponse:
type: object
properties:
@@ -2602,4 +2780,154 @@ components:
example: '09:00'
close_time:
type: string
- example: '18:00'
\ No newline at end of file
+ example: '18:00'
+
+ ChatListResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Success get chat list
+ results:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/Chat'
+ pagination:
+ type: object
+ properties:
+ limit:
+ type: integer
+ example: 25
+ offset:
+ type: integer
+ example: 0
+ total:
+ type: integer
+ example: 150
+
+ Chat:
+ type: object
+ properties:
+ jid:
+ type: string
+ example: '[email protected]'
+ description: Chat JID identifier
+ name:
+ type: string
+ example: 'John Doe'
+ description: Chat display name
+ last_message_time:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:30:00Z'
+ description: Timestamp of the last message
+ ephemeral_expiration:
+ type: integer
+ example: 0
+ description: Ephemeral message expiration time in seconds (0 = disabled)
+ created_at:
+ type: string
+ format: date-time
+ example: '2024-01-10T08:00:00Z'
+ description: Chat creation timestamp
+ updated_at:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:30:00Z'
+ description: Chat last update timestamp
+
+ ChatMessagesResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Success get chat messages
+ results:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/ChatMessage'
+ pagination:
+ type: object
+ properties:
+ limit:
+ type: integer
+ example: 50
+ offset:
+ type: integer
+ example: 0
+ total:
+ type: integer
+ example: 1250
+ chat_info:
+ $ref: '#/components/schemas/Chat'
+
+ ChatMessage:
+ type: object
+ properties:
+ id:
+ type: string
+ example: '3EB0B430B6F8F1D0E053AC120E0A9E5C'
+ description: Message ID
+ chat_jid:
+ type: string
+ example: '[email protected]'
+ description: Chat JID this message belongs to
+ sender_jid:
+ type: string
+ example: '[email protected]'
+ description: Sender JID
+ content:
+ type: string
+ example: 'Hello, how are you?'
+ description: Message text content
+ timestamp:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:30:00Z'
+ description: Message timestamp
+ is_from_me:
+ type: boolean
+ example: false
+ description: Whether this message was sent by the current user
+ media_type:
+ type: string
+ example: 'image'
+ nullable: true
+ description: Type of media (image, video, audio, document, etc.)
+ filename:
+ type: string
+ example: 'photo.jpg'
+ nullable: true
+ description: Original filename for media messages
+ url:
+ type: string
+ example: 'https://media.example.com/file.jpg'
+ nullable: true
+ description: Media file URL
+ file_length:
+ type: integer
+ example: 1024768
+ nullable: true
+ description: File size in bytes for media messages
+ created_at:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:30:00Z'
+ description: Record creation timestamp
+ updated_at:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:30:00Z'
+ description: Record last update timestamp
\ No newline at end of file
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 614ee87f..3cb8af6b 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -82,6 +82,7 @@ func restServer(_ *cobra.Command, _ []string) {
// Rest
rest.InitRestApp(app, appUsecase)
+ rest.InitRestChat(app, chatUsecase)
rest.InitRestSend(app, sendUsecase)
rest.InitRestUser(app, userUsecase)
rest.InitRestMessage(app, messageUsecase)
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 7d7b7555..4f3a5cca 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -10,6 +10,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
domainNewsletter "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/newsletter"
@@ -42,6 +43,7 @@ var (
// Usecase
appUsecase domainApp.IAppUsecase
+ chatUsecase domainChat.IChatUsecase
sendUsecase domainSend.ISendUsecase
userUsecase domainUser.IUserUsecase
messageUsecase domainMessage.IMessageUsecase
@@ -185,7 +187,9 @@ func initFlags() {
func initApp() {
if config.AppDebug {
config.WhatsappLogLevel = "DEBUG"
+ logrus.SetLevel(logrus.DebugLevel)
}
+
//preparing folder if not exist
err := utils.CreateFolder(config.PathQrCode, config.PathSendItems, config.PathStorages, config.PathMedia)
if err != nil {
@@ -205,9 +209,10 @@ func initApp() {
// Usecase
appUsecase = usecase.NewAppService(whatsappDB, chatStorageRepo)
+ chatUsecase = usecase.NewChatService(chatStorageRepo)
sendUsecase = usecase.NewSendService(appUsecase, chatStorageRepo)
userUsecase = usecase.NewUserService()
- messageUsecase = usecase.NewMessageService()
+ messageUsecase = usecase.NewMessageService(chatStorageRepo)
groupUsecase = usecase.NewGroupService()
newsletterUsecase = usecase.NewNewsletterService()
}
diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.go
new file mode 100644
index 00000000..659d44c5
--- /dev/null
+++ b/src/domains/chat/chat.go
@@ -0,0 +1,62 @@
+package chat
+
+// Request and Response structures for chat operations
+
+type ListChatsRequest struct {
+ Limit int `json:"limit" query:"limit"`
+ Offset int `json:"offset" query:"offset"`
+ Search string `json:"search" query:"search"`
+ HasMedia bool `json:"has_media" query:"has_media"`
+}
+
+type ListChatsResponse struct {
+ Data []ChatInfo `json:"data"`
+ Pagination PaginationResponse `json:"pagination"`
+}
+
+type GetChatMessagesRequest struct {
+ ChatJID string `json:"chat_jid" uri:"chat_jid"`
+ Limit int `json:"limit" query:"limit"`
+ Offset int `json:"offset" query:"offset"`
+ StartTime *string `json:"start_time" query:"start_time"`
+ EndTime *string `json:"end_time" query:"end_time"`
+ MediaOnly bool `json:"media_only" query:"media_only"`
+ IsFromMe *bool `json:"is_from_me" query:"is_from_me"`
+ Search string `json:"search" query:"search"`
+}
+
+type GetChatMessagesResponse struct {
+ Data []MessageInfo `json:"data"`
+ Pagination PaginationResponse `json:"pagination"`
+ ChatInfo ChatInfo `json:"chat_info"`
+}
+
+type ChatInfo struct {
+ JID string `json:"jid"`
+ Name string `json:"name"`
+ LastMessageTime string `json:"last_message_time"`
+ EphemeralExpiration uint32 `json:"ephemeral_expiration"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+type MessageInfo struct {
+ ID string `json:"id"`
+ ChatJID string `json:"chat_jid"`
+ SenderJID string `json:"sender_jid"`
+ Content string `json:"content"`
+ Timestamp string `json:"timestamp"`
+ IsFromMe bool `json:"is_from_me"`
+ MediaType string `json:"media_type"`
+ Filename string `json:"filename"`
+ URL string `json:"url"`
+ FileLength uint64 `json:"file_length"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+type PaginationResponse struct {
+ Limit int `json:"limit"`
+ Offset int `json:"offset"`
+ Total int `json:"total"`
+}
diff --git a/src/domains/chat/interfaces.go b/src/domains/chat/interfaces.go
new file mode 100644
index 00000000..eedeb492
--- /dev/null
+++ b/src/domains/chat/interfaces.go
@@ -0,0 +1,11 @@
+package chat
+
+import (
+ "context"
+)
+
+// IChatUsecase defines the interface for chat-related operations
+type IChatUsecase interface {
+ ListChats(ctx context.Context, request ListChatsRequest) (response ListChatsResponse, err error)
+ GetChatMessages(ctx context.Context, request GetChatMessagesRequest) (response GetChatMessagesResponse, err error)
+}
\ No newline at end of file
diff --git a/src/domains/message/interfaces.go b/src/domains/message/interfaces.go
index 65b40c23..b39b8595 100644
--- a/src/domains/message/interfaces.go
+++ b/src/domains/message/interfaces.go
@@ -18,7 +18,7 @@ type IMessageManagement interface {
StarMessage(ctx context.Context, request StarRequest) (err error)
}
-// IMessageUsecase combines all message interfaces for backward compatibility
+// IMessageUsecase combines all message interfaces
type IMessageUsecase interface {
IMessageActions
IMessageManagement
diff --git a/src/domains/message/message.go b/src/domains/message/message.go
index e265752d..ef38312d 100644
--- a/src/domains/message/message.go
+++ b/src/domains/message/message.go
@@ -1,9 +1,5 @@
package message
-// NOTE: imports moved to interfaces.go
-
-// NOTE: IMessageUsecase is now defined in interfaces.go with proper segregation
-
type GenericResponse struct {
MessageID string `json:"message_id"`
Status string `json:"status"`
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 622b55d0..b1f60607 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -596,6 +596,9 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS
// Get or create chat
chatName := chatStorageRepo.GetChatNameWithPushName(jid, chatJID, "", displayName)
+ // Extract ephemeral expiration from conversation
+ ephemeralExpiration := conv.GetEphemeralExpiration()
+
// Process messages in the conversation
messages := conv.GetMessages()
log.Debugf("Processing %d messages for chat %s", len(messages), chatJID)
@@ -663,9 +666,9 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS
}
}
- // Convert timestamp from Unix milliseconds to time.Time
- // WhatsApp timestamps are in milliseconds, not seconds
- timestamp := time.UnixMilli(int64(msg.GetMessageTimestamp()))
+ // Convert timestamp from Unix seconds to time.Time
+ // WhatsApp history sync timestamps are in seconds, not milliseconds
+ timestamp := time.Unix(int64(msg.GetMessageTimestamp()), 0)
// Track latest timestamp
if timestamp.After(latestTimestamp) {
@@ -698,7 +701,7 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS
JID: chatJID,
Name: chatName,
LastMessageTime: latestTimestamp,
- EphemeralExpiration: 0, // Will be updated from individual messages
+ EphemeralExpiration: ephemeralExpiration,
}
// Store or update the chat
@@ -720,12 +723,12 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS
}
// processPushNames processes push names from history sync to update chat names
-func processPushNames(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo *chatstorage.Storage) error {
+func processPushNames(_ context.Context, data *waHistorySync.HistorySync, chatStorageRepo *chatstorage.Storage) error {
pushnames := data.GetPushnames()
log.Infof("Processing %d push names from history sync", len(pushnames))
for _, pushname := range pushnames {
- jidStr := pushname.GetId()
+ jidStr := pushname.GetID()
name := pushname.GetPushname()
if jidStr == "" || name == "" {
diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.go
index 37d8f140..d6e7f387 100644
--- a/src/infrastructure/whatsapp/webhook.go
+++ b/src/infrastructure/whatsapp/webhook.go
@@ -44,6 +44,9 @@ func createPayload(ctx context.Context, evt *events.Message) (map[string]interfa
body := make(map[string]interface{})
+ body["sender_id"] = evt.Info.Sender.User
+ body["chat_id"] = evt.Info.Chat.User
+
if from := evt.Info.SourceString(); from != "" {
body["from"] = from
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index 23247391..5d756eef 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -242,58 +242,118 @@ func ExtractMediaInfo(msg *waE2E.Message) (mediaType string, filename string, ur
// ExtractEphemeralExpiration extracts ephemeral expiration from a WhatsApp message
func ExtractEphemeralExpiration(msg *waE2E.Message) uint32 {
+ logrus.Info("ExtractEphemeralExpiration: Starting extraction process")
+
if msg == nil {
+ logrus.Debug("ExtractEphemeralExpiration: Message is nil, returning 0")
return 0
}
+ logrus.Debug("ExtractEphemeralExpiration: Message is valid, checking message types")
+
// Check extended text message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for extended text message")
if extendedText := msg.GetExtendedTextMessage(); extendedText != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Extended text message found, checking context info")
if contextInfo := extendedText.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in extended text message")
+ return expiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Extended text message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No extended text message found")
}
// Check regular conversation message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for regular conversation message")
if msg.GetConversation() != "" {
+ logrus.Debug("ExtractEphemeralExpiration: Regular conversation message found, but no context info available for this type")
// Regular text messages might have context info too
// This would need to be checked based on the actual protobuf structure
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No regular conversation message found")
}
// Check image message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for image message")
if img := msg.GetImageMessage(); img != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Image message found, checking context info")
if contextInfo := img.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in image message")
+ return expiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Image message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No image message found")
}
// Check video message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for video message")
if vid := msg.GetVideoMessage(); vid != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Video message found, checking context info")
if contextInfo := vid.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in video message")
+ return expiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Video message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No video message found")
}
// Check audio message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for audio message")
if aud := msg.GetAudioMessage(); aud != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Audio message found, checking context info")
if contextInfo := aud.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in audio message")
+ return expiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Audio message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No audio message found")
}
// Check document message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for document message")
if doc := msg.GetDocumentMessage(); doc != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Document message found, checking context info")
if contextInfo := doc.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in document message")
+ return expiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Document message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No document message found")
}
// Check sticker message
+ logrus.Debug("ExtractEphemeralExpiration: Checking for sticker message")
if sticker := msg.GetStickerMessage(); sticker != nil {
+ logrus.Debug("ExtractEphemeralExpiration: Sticker message found, checking context info")
if contextInfo := sticker.GetContextInfo(); contextInfo != nil {
- return contextInfo.GetExpiration()
+ expiration := contextInfo.GetExpiration()
+ logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in sticker message")
+ return expiration
+ }
+ logrus.Debug("ExtractEphemeralExpiration: Sticker message has no context info")
+ } else {
+ logrus.Debug("ExtractEphemeralExpiration: No sticker message found")
+ }
+
+ if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
+ if ephemeralExpiration := protocolMessage.GetEphemeralExpiration(); ephemeralExpiration != 0 {
+ logrus.WithField("expiration", ephemeralExpiration).Debug("ExtractEphemeralExpiration: Found expiration in protocol message")
+ return ephemeralExpiration
}
+ logrus.Debug("ExtractEphemeralExpiration: Protocol message has no expiration")
}
+ logrus.Debug("ExtractEphemeralExpiration: No expiration found in any message type, returning 0")
return 0
}
diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.go
new file mode 100644
index 00000000..9513655b
--- /dev/null
+++ b/src/ui/rest/chat.go
@@ -0,0 +1,78 @@
+package rest
+
+import (
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v2"
+)
+
+type Chat struct {
+ Service domainChat.IChatUsecase
+}
+
+func InitRestChat(app *fiber.App, service domainChat.IChatUsecase) Chat {
+ rest := Chat{Service: service}
+
+ // Chat endpoints
+ app.Get("/chats", rest.ListChats)
+ app.Get("/chat/:chat_jid/messages", rest.GetChatMessages)
+
+ return rest
+}
+
+func (controller *Chat) ListChats(c *fiber.Ctx) error {
+ var request domainChat.ListChatsRequest
+
+ // Parse query parameters
+ request.Limit = c.QueryInt("limit", 25)
+ request.Offset = c.QueryInt("offset", 0)
+ request.Search = c.Query("search", "")
+ request.HasMedia = c.QueryBool("has_media", false)
+
+ response, err := controller.Service.ListChats(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Success get chat list",
+ Results: response,
+ })
+}
+
+func (controller *Chat) GetChatMessages(c *fiber.Ctx) error {
+ var request domainChat.GetChatMessagesRequest
+
+ // Parse path parameter
+ request.ChatJID = c.Params("chat_jid")
+
+ // Parse query parameters
+ request.Limit = c.QueryInt("limit", 50)
+ request.Offset = c.QueryInt("offset", 0)
+ request.MediaOnly = c.QueryBool("media_only", false)
+ request.Search = c.Query("search", "")
+
+ // Parse time filters
+ if startTime := c.Query("start_time"); startTime != "" {
+ request.StartTime = &startTime
+ }
+ if endTime := c.Query("end_time"); endTime != "" {
+ request.EndTime = &endTime
+ }
+
+ // Parse is_from_me filter
+ if isFromMeStr := c.Query("is_from_me"); isFromMeStr != "" {
+ isFromMe := c.QueryBool("is_from_me")
+ request.IsFromMe = &isFromMe
+ }
+
+ response, err := controller.Service.GetChatMessages(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Success get chat messages",
+ Results: response,
+ })
+}
diff --git a/src/ui/rest/message.go b/src/ui/rest/message.go
index 0171da43..0a130d14 100644
--- a/src/ui/rest/message.go
+++ b/src/ui/rest/message.go
@@ -12,6 +12,8 @@ type Message struct {
func InitRestMessage(app *fiber.App, service domainMessage.IMessageUsecase) Message {
rest := Message{Service: service}
+
+ // Message action endpoints
app.Post("/message/:message_id/reaction", rest.ReactMessage)
app.Post("/message/:message_id/revoke", rest.RevokeMessage)
app.Post("/message/:message_id/delete", rest.DeleteMessage)
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
new file mode 100644
index 00000000..be3422a7
--- /dev/null
+++ b/src/usecase/chat.go
@@ -0,0 +1,201 @@
+package usecase
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
+ "github.com/sirupsen/logrus"
+)
+
+type serviceChat struct {
+ chatStorageRepo *chatstorage.Storage
+}
+
+func NewChatService(chatStorageRepo *chatstorage.Storage) domainChat.IChatUsecase {
+ return &serviceChat{
+ chatStorageRepo: chatStorageRepo,
+ }
+}
+
+func (service serviceChat) ListChats(ctx context.Context, request domainChat.ListChatsRequest) (response domainChat.ListChatsResponse, err error) {
+ if err = validations.ValidateListChats(ctx, &request); err != nil {
+ return response, err
+ }
+
+ // Create filter from request
+ filter := &chatstorage.ChatFilter{
+ Limit: request.Limit,
+ Offset: request.Offset,
+ SearchName: request.Search,
+ HasMedia: request.HasMedia,
+ }
+
+ // Get chats from storage
+ chats, err := service.chatStorageRepo.Repository().GetChats(filter)
+ if err != nil {
+ logrus.WithError(err).Error("Failed to get chats from storage")
+ return response, err
+ }
+
+ // Get total count for pagination
+ totalCount, err := service.chatStorageRepo.Repository().GetTotalChatCount()
+ if err != nil {
+ logrus.WithError(err).Error("Failed to get total chat count")
+ // Continue with partial data
+ totalCount = 0
+ }
+
+ // Convert entities to domain objects
+ chatInfos := make([]domainChat.ChatInfo, 0, len(chats))
+ for _, chat := range chats {
+ chatInfo := domainChat.ChatInfo{
+ JID: chat.JID,
+ Name: chat.Name,
+ LastMessageTime: chat.LastMessageTime.Format(time.RFC3339),
+ EphemeralExpiration: chat.EphemeralExpiration,
+ CreatedAt: chat.CreatedAt.Format(time.RFC3339),
+ UpdatedAt: chat.UpdatedAt.Format(time.RFC3339),
+ }
+ chatInfos = append(chatInfos, chatInfo)
+ }
+
+ // Create pagination response
+ pagination := domainChat.PaginationResponse{
+ Limit: request.Limit,
+ Offset: request.Offset,
+ Total: int(totalCount),
+ }
+
+ response.Data = chatInfos
+ response.Pagination = pagination
+
+ logrus.WithFields(logrus.Fields{
+ "total_chats": len(chatInfos),
+ "limit": request.Limit,
+ "offset": request.Offset,
+ }).Info("Listed chats successfully")
+
+ return response, nil
+}
+
+func (service serviceChat) GetChatMessages(ctx context.Context, request domainChat.GetChatMessagesRequest) (response domainChat.GetChatMessagesResponse, err error) {
+ if err = validations.ValidateGetChatMessages(ctx, &request); err != nil {
+ return response, err
+ }
+
+ // Get chat info first
+ chat, err := service.chatStorageRepo.Repository().GetChat(request.ChatJID)
+ if err != nil {
+ logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get chat info")
+ return response, err
+ }
+ if chat == nil {
+ return response, fmt.Errorf("chat with JID %s not found", request.ChatJID)
+ }
+
+ // Create message filter from request
+ filter := &chatstorage.MessageFilter{
+ ChatJID: request.ChatJID,
+ Limit: request.Limit,
+ Offset: request.Offset,
+ MediaOnly: request.MediaOnly,
+ IsFromMe: request.IsFromMe,
+ }
+
+ // Parse time filters if provided
+ if request.StartTime != nil && *request.StartTime != "" {
+ startTime, err := time.Parse(time.RFC3339, *request.StartTime)
+ if err != nil {
+ return response, fmt.Errorf("invalid start_time format: %v", err)
+ }
+ filter.StartTime = &startTime
+ }
+
+ if request.EndTime != nil && *request.EndTime != "" {
+ endTime, err := time.Parse(time.RFC3339, *request.EndTime)
+ if err != nil {
+ return response, fmt.Errorf("invalid end_time format: %v", err)
+ }
+ filter.EndTime = &endTime
+ }
+
+ // Get messages from storage
+ var messages []*chatstorage.Message
+ if request.Search != "" {
+ // Use search functionality if search query is provided
+ messages, err = service.chatStorageRepo.Repository().SearchMessages(request.ChatJID, request.Search, request.Limit)
+ if err != nil {
+ logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to search messages")
+ return response, err
+ }
+ } else {
+ // Use regular filter
+ messages, err = service.chatStorageRepo.Repository().GetMessages(filter)
+ if err != nil {
+ logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get messages")
+ return response, err
+ }
+ }
+
+ // Get total message count for pagination
+ totalCount, err := service.chatStorageRepo.Repository().GetChatMessageCount(request.ChatJID)
+ if err != nil {
+ logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get message count")
+ // Continue with partial data
+ totalCount = 0
+ }
+
+ // Convert entities to domain objects
+ messageInfos := make([]domainChat.MessageInfo, 0, len(messages))
+ for _, message := range messages {
+ messageInfo := domainChat.MessageInfo{
+ ID: message.ID,
+ ChatJID: message.ChatJID,
+ SenderJID: message.Sender,
+ Content: message.Content,
+ Timestamp: message.Timestamp.Format(time.RFC3339),
+ IsFromMe: message.IsFromMe,
+ MediaType: message.MediaType,
+ Filename: message.Filename,
+ URL: message.URL,
+ FileLength: message.FileLength,
+ CreatedAt: message.CreatedAt.Format(time.RFC3339),
+ UpdatedAt: message.UpdatedAt.Format(time.RFC3339),
+ }
+ messageInfos = append(messageInfos, messageInfo)
+ }
+
+ // Create chat info for response
+ chatInfo := domainChat.ChatInfo{
+ JID: chat.JID,
+ Name: chat.Name,
+ LastMessageTime: chat.LastMessageTime.Format(time.RFC3339),
+ EphemeralExpiration: chat.EphemeralExpiration,
+ CreatedAt: chat.CreatedAt.Format(time.RFC3339),
+ UpdatedAt: chat.UpdatedAt.Format(time.RFC3339),
+ }
+
+ // Create pagination response
+ pagination := domainChat.PaginationResponse{
+ Limit: request.Limit,
+ Offset: request.Offset,
+ Total: int(totalCount),
+ }
+
+ response.Data = messageInfos
+ response.Pagination = pagination
+ response.ChatInfo = chatInfo
+
+ logrus.WithFields(logrus.Fields{
+ "chat_jid": request.ChatJID,
+ "total_messages": len(messageInfos),
+ "limit": request.Limit,
+ "offset": request.Offset,
+ }).Info("Retrieved chat messages successfully")
+
+ return response, nil
+}
diff --git a/src/usecase/message.go b/src/usecase/message.go
index 69145c41..921fa3bc 100644
--- a/src/usecase/message.go
+++ b/src/usecase/message.go
@@ -6,6 +6,7 @@ import (
"time"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
@@ -18,10 +19,14 @@ import (
"google.golang.org/protobuf/proto"
)
-type serviceMessage struct{}
+type serviceMessage struct {
+ chatStorageRepo *chatstorage.Storage
+}
-func NewMessageService() domainMessage.IMessageUsecase {
- return &serviceMessage{}
+func NewMessageService(chatStorageRepo *chatstorage.Storage) domainMessage.IMessageUsecase {
+ return &serviceMessage{
+ chatStorageRepo: chatStorageRepo,
+ }
}
func (service serviceMessage) MarkAsRead(ctx context.Context, request domainMessage.MarkAsReadRequest) (response domainMessage.GenericResponse, err error) {
@@ -177,3 +182,4 @@ func (service serviceMessage) StarMessage(ctx context.Context, request domainMes
}
return nil
}
+
diff --git a/src/validations/chat_validation.go b/src/validations/chat_validation.go
new file mode 100644
index 00000000..ae60ee80
--- /dev/null
+++ b/src/validations/chat_validation.go
@@ -0,0 +1,46 @@
+package validations
+
+import (
+ "context"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ validation "github.com/go-ozzo/ozzo-validation/v4"
+)
+
+func ValidateListChats(ctx context.Context, request *domainChat.ListChatsRequest) error {
+ // Set default limit if not provided
+ if request.Limit == 0 {
+ request.Limit = 25
+ }
+
+ err := validation.ValidateStructWithContext(ctx, request,
+ validation.Field(&request.Limit, validation.Min(1), validation.Max(100)),
+ validation.Field(&request.Offset, validation.Min(0)),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
+
+func ValidateGetChatMessages(ctx context.Context, request *domainChat.GetChatMessagesRequest) error {
+ // Set default limit if not provided
+ if request.Limit == 0 {
+ request.Limit = 50
+ }
+
+ err := validation.ValidateStructWithContext(ctx, request,
+ validation.Field(&request.ChatJID, validation.Required),
+ validation.Field(&request.Limit, validation.Min(1), validation.Max(100)),
+ validation.Field(&request.Offset, validation.Min(0)),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
diff --git a/src/validations/message_validation.go b/src/validations/message_validation.go
index 35bff403..47b9dc94 100644
--- a/src/validations/message_validation.go
+++ b/src/validations/message_validation.go
@@ -3,7 +3,6 @@ package validations
import (
"context"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
validation "github.com/go-ozzo/ozzo-validation/v4"
@@ -50,7 +49,7 @@ func ValidateUpdateMessage(ctx context.Context, request domainMessage.UpdateMess
return nil
}
-func ValidateReactMessage(ctx context.Context, request message.ReactionRequest) error {
+func ValidateReactMessage(ctx context.Context, request domainMessage.ReactionRequest) error {
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
validation.Field(&request.MessageID, validation.Required),