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(group): add comprehensive group management functionality (#319)

Aldino Kemal30770786528d
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 479e7ea9..d902b374 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 6.4.0
+ version: 6.5.0
description: This API is used for sending whatsapp via API
servers:
- url: http://localhost:3000
@@ -1581,6 +1581,218 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /group/photo:
+ post:
+ operationId: setGroupPhoto
+ tags:
+ - group
+ summary: Set group photo
+ requestBody:
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ properties:
+ group_id:
+ type: string
+ example: '[email protected]'
+ description: The group ID
+ photo:
+ type: string
+ format: binary
+ description: Group photo to upload (JPEG format recommended). Leave empty to remove photo.
+ required:
+ - group_id
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SetGroupPhotoResponse'
+ '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'
+ /group/name:
+ post:
+ operationId: setGroupName
+ tags:
+ - group
+ summary: Set group name
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ group_id:
+ type: string
+ example: '[email protected]'
+ description: The group ID
+ name:
+ type: string
+ example: 'New Group Name'
+ description: The new group name (max 25 characters)
+ maxLength: 25
+ required:
+ - group_id
+ - name
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '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'
+ /group/locked:
+ post:
+ operationId: setGroupLocked
+ tags:
+ - group
+ summary: Set group locked status
+ description: Lock/unlock group so only admins can modify group info
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ group_id:
+ type: string
+ example: '[email protected]'
+ description: The group ID
+ locked:
+ type: boolean
+ example: true
+ description: Whether to lock the group (true) or unlock it (false)
+ required:
+ - group_id
+ - locked
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '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'
+ /group/announce:
+ post:
+ operationId: setGroupAnnounce
+ tags:
+ - group
+ summary: Set group announce mode
+ description: Enable/disable announce mode so only admins can send messages
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ group_id:
+ type: string
+ example: '[email protected]'
+ description: The group ID
+ announce:
+ type: boolean
+ example: true
+ description: Whether to enable announce mode (true) or disable it (false)
+ required:
+ - group_id
+ - announce
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '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'
+ /group/topic:
+ post:
+ operationId: setGroupTopic
+ tags:
+ - group
+ summary: Set group topic
+ description: Set or remove group topic/description
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ group_id:
+ type: string
+ example: '[email protected]'
+ description: The group ID
+ topic:
+ type: string
+ example: 'Welcome to our group! Please follow the rules.'
+ description: The group topic/description. Leave empty to remove the topic.
+ required:
+ - group_id
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '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'
/newsletter/unfollow:
post:
operationId: unfollowNewsletter
@@ -1676,6 +1888,25 @@ components:
message:
type: string
example: Participant added
+ SetGroupPhotoResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Success update group photo
+ results:
+ type: object
+ properties:
+ picture_id:
+ type: string
+ example: "1647874123"
+ description: The ID of the uploaded picture, or 'remove' if photo was removed
+ message:
+ type: string
+ example: Success update group photo
UserGroupResponse:
type: object
diff --git a/src/cmd/mcp.go b/src/cmd/mcp.go
index 7f0d8461..7c88b64f 100644
--- a/src/cmd/mcp.go
+++ b/src/cmd/mcp.go
@@ -2,7 +2,8 @@ package cmd
import (
"fmt"
- "log"
+
+ "github.com/sirupsen/logrus"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp"
@@ -52,11 +53,11 @@ func mcpServer(_ *cobra.Command, _ []string) {
// Start the SSE server
addr := fmt.Sprintf("%s:%s", config.McpHost, config.McpPort)
- log.Printf("Starting WhatsApp MCP SSE server on %s", addr)
- log.Printf("SSE endpoint: http://%s:%s/sse", config.McpHost, config.McpPort)
- log.Printf("Message endpoint: http://%s:%s/message", config.McpHost, config.McpPort)
+ logrus.Printf("Starting WhatsApp MCP SSE server on %s", addr)
+ logrus.Printf("SSE endpoint: http://%s:%s/sse", config.McpHost, config.McpPort)
+ logrus.Printf("Message endpoint: http://%s:%s/message", config.McpHost, config.McpPort)
if err := sseServer.Start(addr); err != nil {
- log.Fatalf("Failed to start SSE server: %v", err)
+ logrus.Fatalf("Failed to start SSE server: %v", err)
}
}
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 6695407b..43f54d44 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -2,7 +2,6 @@ package cmd
import (
"fmt"
- "log"
"net/http"
"strings"
@@ -18,6 +17,7 @@ import (
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/template/html/v2"
+ "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -70,7 +70,7 @@ func restServer(_ *cobra.Command, _ []string) {
for _, basicAuth := range config.AppBasicAuthCredential {
ba := strings.Split(basicAuth, ":")
if len(ba) != 2 {
- log.Fatalln("Basic auth is not valid, please this following format <user>:<secret>")
+ logrus.Fatalln("Basic auth is not valid, please this following format <user>:<secret>")
}
account[ba[0]] = ba[1]
}
@@ -111,6 +111,6 @@ func restServer(_ *cobra.Command, _ []string) {
}
if err := app.Listen(":" + config.AppPort); err != nil {
- log.Fatalln("Failed to start: ", err.Error())
+ logrus.Fatalln("Failed to start: ", err.Error())
}
}
diff --git a/src/domains/group/group.go b/src/domains/group/group.go
index b6fd4371..f046ddd8 100644
--- a/src/domains/group/group.go
+++ b/src/domains/group/group.go
@@ -2,6 +2,7 @@ package group
import (
"context"
+ "mime/multipart"
"time"
"go.mau.fi/whatsmeow"
@@ -14,6 +15,11 @@ type IGroupUsecase interface {
ManageParticipant(ctx context.Context, request ParticipantRequest) (result []ParticipantStatus, err error)
GetGroupRequestParticipants(ctx context.Context, request GetGroupRequestParticipantsRequest) (result []GetGroupRequestParticipantsResponse, err error)
ManageGroupRequestParticipants(ctx context.Context, request GroupRequestParticipantsRequest) (result []ParticipantStatus, err error)
+ SetGroupPhoto(ctx context.Context, request SetGroupPhotoRequest) (pictureID string, err error)
+ SetGroupName(ctx context.Context, request SetGroupNameRequest) (err error)
+ SetGroupLocked(ctx context.Context, request SetGroupLockedRequest) (err error)
+ SetGroupAnnounce(ctx context.Context, request SetGroupAnnounceRequest) (err error)
+ SetGroupTopic(ctx context.Context, request SetGroupTopicRequest) (err error)
}
type JoinGroupWithLinkRequest struct {
@@ -55,3 +61,33 @@ type GroupRequestParticipantsRequest struct {
Participants []string `json:"participants" form:"participants"`
Action whatsmeow.ParticipantRequestChange `json:"action" form:"action"`
}
+
+type SetGroupPhotoRequest struct {
+ GroupID string `json:"group_id" form:"group_id"`
+ Photo *multipart.FileHeader `json:"photo" form:"photo"`
+}
+
+type SetGroupPhotoResponse struct {
+ PictureID string `json:"picture_id"`
+ Message string `json:"message"`
+}
+
+type SetGroupNameRequest struct {
+ GroupID string `json:"group_id" form:"group_id"`
+ Name string `json:"name" form:"name"`
+}
+
+type SetGroupLockedRequest struct {
+ GroupID string `json:"group_id" form:"group_id"`
+ Locked bool `json:"locked" form:"locked"`
+}
+
+type SetGroupAnnounceRequest struct {
+ GroupID string `json:"group_id" form:"group_id"`
+ Announce bool `json:"announce" form:"announce"`
+}
+
+type SetGroupTopicRequest struct {
+ GroupID string `json:"group_id" form:"group_id"`
+ Topic string `json:"topic" form:"topic"`
+}
diff --git a/src/pkg/utils/environment.go b/src/pkg/utils/environment.go
index 6df7836c..148bdcce 100644
--- a/src/pkg/utils/environment.go
+++ b/src/pkg/utils/environment.go
@@ -6,7 +6,7 @@ import (
"strconv"
"time"
- log "github.com/sirupsen/logrus"
+ "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
@@ -28,19 +28,19 @@ func Env[T any](key string, defValue ...T) T {
func MustHaveEnv(key string) string {
env := viper.GetString(key)
if env == "" {
- log.Warn(context.Background(), map[string]interface{}{
+ logrus.Warn(context.Background(), map[string]interface{}{
"field": key,
}, "variable is not well set, reading from .env file")
viper.SetConfigFile(".env")
viper.SetConfigType("env")
err := viper.ReadInConfig()
if err != nil {
- log.Fatal(err, "can't read .env file")
+ logrus.Fatal(err, "can't read .env file")
}
env = viper.GetString(key)
}
if env == "" {
- log.Fatal(fmt.Sprintf("%s is not well set", key))
+ logrus.Fatal(fmt.Sprintf("%s is not well set", key))
}
return env
}
@@ -56,7 +56,7 @@ func MustHaveEnvInt(key string) int {
env := MustHaveEnv(key)
number, err := strconv.ParseInt(env, 10, 64)
if err != nil {
- log.Fatal(fmt.Sprintf("%s is not well set", key))
+ logrus.Fatal(fmt.Sprintf("%s is not well set", key))
}
return int(number)
}
@@ -66,7 +66,7 @@ func MustHaveEnvMinuteDuration(key string) time.Duration {
env := MustHaveEnv(key)
number, err := strconv.ParseInt(env, 10, 64)
if err != nil {
- log.Fatal(fmt.Sprintf("%s is not well set", key))
+ logrus.Fatal(fmt.Sprintf("%s is not well set", key))
}
return time.Duration(number) * time.Minute
diff --git a/src/pkg/utils/image_utils.go b/src/pkg/utils/image_utils.go
new file mode 100644
index 00000000..f84264ed
--- /dev/null
+++ b/src/pkg/utils/image_utils.go
@@ -0,0 +1,180 @@
+package utils
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ "image/jpeg"
+ "io"
+ "mime/multipart"
+
+ "github.com/disintegration/imaging"
+)
+
+const (
+ // WhatsApp group photo constraints
+ MaxGroupPhotoSize = 100 * 1024 // 100KB
+ GroupPhotoQuality = 80 // JPEG quality
+ MaxGroupPhotoDimension = 640 // Max width/height in pixels
+)
+
+// ProcessGroupPhoto processes an image for WhatsApp group photo requirements:
+// - Converts to JPEG format
+// - Crops to 1:1 aspect ratio (square)
+// - Resizes to fit within MaxGroupPhotoDimension
+// - Compresses to stay under MaxGroupPhotoSize
+func ProcessGroupPhoto(file *multipart.FileHeader) (*bytes.Buffer, error) {
+ // Open the uploaded file
+ src, err := file.Open()
+ if err != nil {
+ return nil, fmt.Errorf("failed to open uploaded file: %w", err)
+ }
+ defer src.Close()
+
+ // Decode the image
+ img, format, err := image.Decode(src)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode image: %w", err)
+ }
+
+ // Handle different input formats
+ switch format {
+ case "jpeg", "png", "webp":
+ // Supported formats
+ default:
+ return nil, fmt.Errorf("unsupported image format: %s (only JPEG, PNG, and WebP are supported)", format)
+ }
+
+ // Crop to 1:1 aspect ratio (square)
+ img = cropToSquare(img)
+
+ // Resize if too large
+ if img.Bounds().Dx() > MaxGroupPhotoDimension || img.Bounds().Dy() > MaxGroupPhotoDimension {
+ img = imaging.Resize(img, MaxGroupPhotoDimension, MaxGroupPhotoDimension, imaging.Lanczos)
+ }
+
+ // Convert to JPEG with compression
+ return compressToJPEG(img, GroupPhotoQuality)
+}
+
+// cropToSquare crops an image to a 1:1 aspect ratio, keeping the center
+func cropToSquare(img image.Image) image.Image {
+ bounds := img.Bounds()
+ width := bounds.Dx()
+ height := bounds.Dy()
+
+ // If already square, return as-is
+ if width == height {
+ return img
+ }
+
+ // Determine the size of the square (minimum of width and height)
+ size := width
+ if height < width {
+ size = height
+ }
+
+ // Calculate crop position to center the square
+ x := (width - size) / 2
+ y := (height - size) / 2
+
+ // Crop to square
+ cropRect := image.Rect(x, y, x+size, y+size)
+ return imaging.Crop(img, cropRect)
+}
+
+// compressToJPEG converts an image to JPEG format with specified quality
+// and tries to compress it to stay under the file size limit
+func compressToJPEG(img image.Image, quality int) (*bytes.Buffer, error) {
+ return compressToJPEGWithDepth(img, quality, 0)
+}
+
+func compressToJPEGWithDepth(img image.Image, quality int, depth int) (*bytes.Buffer, error) {
+ const maxDepth = 10 // Prevent infinite recursion
+ if depth > maxDepth {
+ return nil, fmt.Errorf("exceeded maximum compression attempts")
+ }
+
+ var buf bytes.Buffer
+
+ // Try with initial quality
+ err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality})
+ if err != nil {
+ return nil, fmt.Errorf("failed to encode JPEG: %w", err)
+ }
+
+ // If file is too large, reduce quality and try again
+ if buf.Len() > MaxGroupPhotoSize && quality > 10 {
+ return compressToJPEGWithDepth(img, quality-10, depth+1)
+ }
+
+ // If still too large even at low quality, resize the image smaller
+ if buf.Len() > MaxGroupPhotoSize {
+ bounds := img.Bounds()
+ newSize := int(float64(bounds.Dx()) * 0.8) // Reduce by 20%
+ if newSize < 100 {
+ return nil, fmt.Errorf("image cannot be compressed enough to meet WhatsApp requirements (max %d bytes)", MaxGroupPhotoSize)
+ }
+
+ resized := imaging.Resize(img, newSize, newSize, imaging.Lanczos)
+ return compressToJPEGWithDepth(resized, quality, depth+1)
+ }
+
+ return &buf, nil
+}
+
+// ValidateGroupPhotoFormat checks if the uploaded file is a supported image format
+func ValidateGroupPhotoFormat(file *multipart.FileHeader) error {
+ if file == nil {
+ return nil // Photo is optional (can be nil to remove photo)
+ }
+
+ // Check content type
+ contentType := file.Header.Get("Content-Type")
+ supportedTypes := map[string]bool{
+ "image/jpeg": true,
+ "image/jpg": true,
+ "image/png": true,
+ "image/webp": true,
+ }
+
+ if contentType != "" && !supportedTypes[contentType] {
+ return fmt.Errorf("unsupported image format: %s (supported: JPEG, PNG, WebP)", contentType)
+ }
+
+ // Check file size (before processing)
+ if file.Size > 10*1024*1024 { // 10MB limit for input
+ return fmt.Errorf("image file too large: %d bytes (max 10MB for processing)", file.Size)
+ }
+
+ // Try to decode the image to verify it's a valid image
+ src, err := file.Open()
+ if err != nil {
+ return fmt.Errorf("failed to open uploaded file: %w", err)
+ }
+ defer src.Close()
+
+ // Read only the first few bytes to detect format
+ header := make([]byte, 512)
+ _, err = src.Read(header)
+ if err != nil && err != io.EOF {
+ return fmt.Errorf("failed to read file header: %w", err)
+ }
+
+ // Reset to beginning
+ if _, err := src.Seek(0, 0); err != nil {
+ return fmt.Errorf("failed to reset file position: %w", err)
+ }
+
+ // Detect image format from header
+ _, format, err := image.DecodeConfig(src)
+ if err != nil {
+ return fmt.Errorf("invalid image file: %w", err)
+ }
+
+ if format != "jpeg" && format != "png" && format != "webp" {
+ return fmt.Errorf("unsupported image format detected: %s", format)
+ }
+
+ return nil
+}
diff --git a/src/ui/rest/group.go b/src/ui/rest/group.go
index c56d5ca3..b9d87443 100644
--- a/src/ui/rest/group.go
+++ b/src/ui/rest/group.go
@@ -3,6 +3,8 @@ package rest
import (
"fmt"
+ "github.com/sirupsen/logrus"
+
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
@@ -26,6 +28,11 @@ func InitRestGroup(app *fiber.App, service domainGroup.IGroupUsecase) Group {
app.Get("/group/participant-requests", rest.ListParticipantRequests)
app.Post("/group/participant-requests/approve", rest.ApproveParticipantRequests)
app.Post("/group/participant-requests/reject", rest.RejectParticipantRequests)
+ app.Post("/group/photo", rest.SetGroupPhoto)
+ app.Post("/group/name", rest.SetGroupName)
+ app.Post("/group/locked", rest.SetGroupLocked)
+ app.Post("/group/announce", rest.SetGroupAnnounce)
+ app.Post("/group/topic", rest.SetGroupTopic)
return rest
}
@@ -164,3 +171,135 @@ func (controller *Group) handleRequestedParticipants(c *fiber.Ctx, action whatsm
Results: result,
})
}
+
+func (controller *Group) SetGroupPhoto(c *fiber.Ctx) error {
+ var request domainGroup.SetGroupPhotoRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ whatsapp.SanitizePhone(&request.GroupID)
+
+ file, err := c.FormFile("photo")
+ if err == nil {
+ logrus.Printf("INFO: Received group photo - Filename: %s, Size: %d bytes, ContentType: %s",
+ file.Filename, file.Size, file.Header.Get("Content-Type"))
+
+ // Basic validation only - processing will be done in usecase
+ if err := utils.ValidateGroupPhotoFormat(file); err != nil {
+ logrus.Printf("ERROR: Group photo validation failed - %v", err)
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "INVALID_IMAGE_FORMAT",
+ Message: fmt.Sprintf("Image validation failed: %v", err),
+ })
+ }
+
+ request.Photo = file
+ } else {
+ logrus.Printf("DEBUG: No photo file provided - Error: %v", err)
+ }
+
+ pictureID, err := controller.Service.SetGroupPhoto(c.UserContext(), request)
+ if err != nil {
+ logrus.Printf("ERROR: WhatsApp service failed to set group photo - %v", err)
+ }
+ utils.PanicIfNeeded(err)
+
+ message := "Success update group photo"
+ if request.Photo == nil {
+ message = "Success remove group photo"
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: message,
+ Results: domainGroup.SetGroupPhotoResponse{
+ PictureID: pictureID,
+ Message: message,
+ },
+ })
+}
+
+func (controller *Group) SetGroupName(c *fiber.Ctx) error {
+ var request domainGroup.SetGroupNameRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ whatsapp.SanitizePhone(&request.GroupID)
+
+ err = controller.Service.SetGroupName(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: fmt.Sprintf("Success update group name to '%s'", request.Name),
+ })
+}
+
+func (controller *Group) SetGroupLocked(c *fiber.Ctx) error {
+ var request domainGroup.SetGroupLockedRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ whatsapp.SanitizePhone(&request.GroupID)
+
+ err = controller.Service.SetGroupLocked(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ message := "Success set group as unlocked"
+ if request.Locked {
+ message = "Success set group as locked"
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: message,
+ })
+}
+
+func (controller *Group) SetGroupAnnounce(c *fiber.Ctx) error {
+ var request domainGroup.SetGroupAnnounceRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ whatsapp.SanitizePhone(&request.GroupID)
+
+ err = controller.Service.SetGroupAnnounce(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ message := "Success disable announce mode"
+ if request.Announce {
+ message = "Success enable announce mode"
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: message,
+ })
+}
+
+func (controller *Group) SetGroupTopic(c *fiber.Ctx) error {
+ var request domainGroup.SetGroupTopicRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ whatsapp.SanitizePhone(&request.GroupID)
+
+ err = controller.Service.SetGroupTopic(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ message := "Success update group topic"
+ if request.Topic == "" {
+ message = "Success remove group topic"
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: message,
+ })
+}
diff --git a/src/ui/websocket/websocket.go b/src/ui/websocket/websocket.go
index fab698eb..3912aa3a 100644
--- a/src/ui/websocket/websocket.go
+++ b/src/ui/websocket/websocket.go
@@ -3,7 +3,8 @@ package websocket
import (
"context"
"encoding/json"
- "log"
+
+ "github.com/sirupsen/logrus"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
"github.com/gofiber/fiber/v2"
@@ -27,24 +28,24 @@ var (
func handleRegister(conn *websocket.Conn) {
Clients[conn] = client{}
- log.Println("connection registered")
+ logrus.Println("connection registered")
}
func handleUnregister(conn *websocket.Conn) {
delete(Clients, conn)
- log.Println("connection unregistered")
+ logrus.Println("connection unregistered")
}
func broadcastMessage(message BroadcastMessage) {
marshalMessage, err := json.Marshal(message)
if err != nil {
- log.Println("marshal error:", err)
+ logrus.Println("marshal error:", err)
return
}
for conn := range Clients {
if err := conn.WriteMessage(websocket.TextMessage, marshalMessage); err != nil {
- log.Println("write error:", err)
+ logrus.Println("write error:", err)
closeConnection(conn)
}
}
@@ -52,10 +53,10 @@ func broadcastMessage(message BroadcastMessage) {
func closeConnection(conn *websocket.Conn) {
if err := conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
- log.Println("write close message error:", err)
+ logrus.Println("write close message error:", err)
}
if err := conn.Close(); err != nil {
- log.Println("close connection error:", err)
+ logrus.Println("close connection error:", err)
}
delete(Clients, conn)
}
@@ -70,7 +71,7 @@ func RunHub() {
handleUnregister(conn)
case message := <-Broadcast:
- log.Println("message received:", message)
+ logrus.Println("message received:", message)
broadcastMessage(message)
}
}
@@ -96,7 +97,7 @@ func RegisterRoutes(app *fiber.App, service domainApp.IAppUsecase) {
messageType, message, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
- log.Println("read error:", err)
+ logrus.Println("read error:", err)
}
return
}
@@ -104,7 +105,7 @@ func RegisterRoutes(app *fiber.App, service domainApp.IAppUsecase) {
if messageType == websocket.TextMessage {
var messageData BroadcastMessage
if err := json.Unmarshal(message, &messageData); err != nil {
- log.Println("unmarshal error:", err)
+ logrus.Println("unmarshal error:", err)
return
}
@@ -117,7 +118,7 @@ func RegisterRoutes(app *fiber.App, service domainApp.IAppUsecase) {
}
}
} else {
- log.Println("unsupported message type:", messageType)
+ logrus.Println("unsupported message type:", messageType)
}
}
}))
diff --git a/src/usecase/group.go b/src/usecase/group.go
index 109aab2b..a77d4be6 100644
--- a/src/usecase/group.go
+++ b/src/usecase/group.go
@@ -4,10 +4,13 @@ import (
"context"
"fmt"
+ "github.com/sirupsen/logrus"
+
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
"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/types"
@@ -194,3 +197,93 @@ func (service serviceGroup) participantToJID(participants []string) ([]types.JID
}
return participantsJID, nil
}
+
+func (service serviceGroup) SetGroupPhoto(ctx context.Context, request domainGroup.SetGroupPhotoRequest) (pictureID string, err error) {
+ if err = validations.ValidateSetGroupPhoto(ctx, request); err != nil {
+ return pictureID, err
+ }
+
+ groupJID, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.GroupID)
+ if err != nil {
+ return pictureID, err
+ }
+
+ var photoBytes []byte
+ if request.Photo != nil {
+ // Process the image for WhatsApp group photo requirements
+ logrus.Printf("Processing group photo: %s (size: %d bytes)", request.Photo.Filename, request.Photo.Size)
+
+ processedImageBuffer, err := utils.ProcessGroupPhoto(request.Photo)
+ if err != nil {
+ logrus.Printf("Failed to process group photo: %v", err)
+ return pictureID, err
+ }
+
+ logrus.Printf("Successfully processed group photo: %d bytes -> %d bytes",
+ request.Photo.Size, processedImageBuffer.Len())
+
+ // Convert buffer to byte slice
+ photoBytes = processedImageBuffer.Bytes()
+ }
+
+ pictureID, err = service.WaCli.SetGroupPhoto(groupJID, photoBytes)
+ if err != nil {
+ logrus.Printf("Failed to set group photo: %v", err)
+ return pictureID, err
+ }
+
+ return pictureID, nil
+}
+
+func (service serviceGroup) SetGroupName(ctx context.Context, request domainGroup.SetGroupNameRequest) (err error) {
+ if err = validations.ValidateSetGroupName(ctx, request); err != nil {
+ return err
+ }
+
+ groupJID, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.GroupID)
+ if err != nil {
+ return err
+ }
+
+ return service.WaCli.SetGroupName(groupJID, request.Name)
+}
+
+func (service serviceGroup) SetGroupLocked(ctx context.Context, request domainGroup.SetGroupLockedRequest) (err error) {
+ if err = validations.ValidateSetGroupLocked(ctx, request); err != nil {
+ return err
+ }
+
+ groupJID, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.GroupID)
+ if err != nil {
+ return err
+ }
+
+ return service.WaCli.SetGroupLocked(groupJID, request.Locked)
+}
+
+func (service serviceGroup) SetGroupAnnounce(ctx context.Context, request domainGroup.SetGroupAnnounceRequest) (err error) {
+ if err = validations.ValidateSetGroupAnnounce(ctx, request); err != nil {
+ return err
+ }
+
+ groupJID, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.GroupID)
+ if err != nil {
+ return err
+ }
+
+ return service.WaCli.SetGroupAnnounce(groupJID, request.Announce)
+}
+
+func (service serviceGroup) SetGroupTopic(ctx context.Context, request domainGroup.SetGroupTopicRequest) (err error) {
+ if err = validations.ValidateSetGroupTopic(ctx, request); err != nil {
+ return err
+ }
+
+ groupJID, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.GroupID)
+ if err != nil {
+ return err
+ }
+
+ // SetGroupTopic with auto-generated IDs (previousID and newID will be handled automatically)
+ return service.WaCli.SetGroupTopic(groupJID, "", "", request.Topic)
+}
diff --git a/src/validations/group_validation.go b/src/validations/group_validation.go
index cd6ab5ac..fba6c00e 100644
--- a/src/validations/group_validation.go
+++ b/src/validations/group_validation.go
@@ -87,3 +87,96 @@ func ValidateManageGroupRequestParticipants(ctx context.Context, request domainG
return nil
}
+
+func ValidateSetGroupPhoto(ctx context.Context, request domainGroup.SetGroupPhotoRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.GroupID, validation.Required),
+ // Photo can be nil to remove the photo, so it's not required
+ // If photo is provided, we could add file type validation here if needed
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ // Optional: Add file type validation if photo is provided
+ if request.Photo != nil {
+ // Check if it's an image file based on content type or filename
+ contentType := request.Photo.Header.Get("Content-Type")
+ if contentType != "" && !isImageContentType(contentType) {
+ return pkgError.ValidationError("uploaded file must be an image")
+ }
+ }
+
+ return nil
+}
+
+// Helper function to check if content type is an image
+func isImageContentType(contentType string) bool {
+ imageTypes := []string{
+ "image/jpeg",
+ "image/jpg",
+ "image/png",
+ "image/gif",
+ "image/webp",
+ }
+
+ for _, imageType := range imageTypes {
+ if contentType == imageType {
+ return true
+ }
+ }
+ return false
+}
+
+func ValidateSetGroupName(ctx context.Context, request domainGroup.SetGroupNameRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.GroupID, validation.Required),
+ validation.Field(&request.Name, validation.Required, validation.Length(1, 25)),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
+
+func ValidateSetGroupLocked(ctx context.Context, request domainGroup.SetGroupLockedRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.GroupID, validation.Required),
+ // Locked is a boolean, no additional validation needed
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
+
+func ValidateSetGroupAnnounce(ctx context.Context, request domainGroup.SetGroupAnnounceRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.GroupID, validation.Required),
+ // Announce is a boolean, no additional validation needed
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
+
+func ValidateSetGroupTopic(ctx context.Context, request domainGroup.SetGroupTopicRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.GroupID, validation.Required),
+ // Topic can be empty to remove the topic, so it's not required
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ return nil
+}
diff --git a/src/views/components/GroupSetAnnounce.js b/src/views/components/GroupSetAnnounce.js
new file mode 100644
index 00000000..b5708eab
--- /dev/null
+++ b/src/views/components/GroupSetAnnounce.js
@@ -0,0 +1,108 @@
+export default {
+ name: 'GroupSetAnnounce',
+ data() {
+ return {
+ loading: false,
+ groupId: '',
+ announce: false,
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalGroupSetAnnounce').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ return this.groupId.trim() !== '';
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalGroupSetAnnounce').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ let response = await window.http.post(`/group/announce`, {
+ group_id: this.groupId,
+ announce: this.announce
+ })
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.groupId = '';
+ this.announce = false;
+ },
+ },
+ template: `
+ <div class="green card" @click="openModal" style="cursor: pointer">
+ <div class="content">
+ <a class="ui green right ribbon label">Group</a>
+ <div class="header">Set Group Announce</div>
+ <div class="description">
+ Enable/disable announce mode for admins only messaging
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal Group Set Announce -->
+ <div class="ui small modal" id="modalGroupSetAnnounce">
+ <i class="close icon"></i>
+ <div class="header">
+ Set Group Announce Mode
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Group ID</label>
+ <input v-model="groupId" type="text"
+ placeholder="[email protected]"
+ aria-label="Group ID">
+ </div>
+
+ <div class="field">
+ <label>Announce Mode</label>
+ <div class="ui toggle checkbox">
+ <input type="checkbox" v-model="announce">
+ <label>{{ announce ? 'Enable announce mode (only admins can send messages)' : 'Disable announce mode (all members can send messages)' }}</label>
+ </div>
+ <div class="ui info message" style="margin-top: 10px;">
+ <div class="header">What does this do?</div>
+ <ul class="list">
+ <li><strong>Announce Mode ON:</strong> Only group admins can send messages to the group</li>
+ <li><strong>Announce Mode OFF:</strong> All group members can send messages</li>
+ </ul>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
+ @click.prevent="handleSubmit" type="button">
+ {{ announce ? 'Enable Announce Mode' : 'Disable Announce Mode' }}
+ <i :class="announce ? 'bullhorn icon' : 'comment icon'"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/components/GroupSetLocked.js b/src/views/components/GroupSetLocked.js
new file mode 100644
index 00000000..615df2d0
--- /dev/null
+++ b/src/views/components/GroupSetLocked.js
@@ -0,0 +1,108 @@
+export default {
+ name: 'GroupSetLocked',
+ data() {
+ return {
+ loading: false,
+ groupId: '',
+ locked: false,
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalGroupSetLocked').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ return this.groupId.trim() !== '';
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalGroupSetLocked').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ let response = await window.http.post(`/group/locked`, {
+ group_id: this.groupId,
+ locked: this.locked
+ })
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.groupId = '';
+ this.locked = false;
+ },
+ },
+ template: `
+ <div class="green card" @click="openModal" style="cursor: pointer">
+ <div class="content">
+ <a class="ui green right ribbon label">Group</a>
+ <div class="header">Set Group Locked</div>
+ <div class="description">
+ Lock/unlock group info editing for admins only
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal Group Set Locked -->
+ <div class="ui small modal" id="modalGroupSetLocked">
+ <i class="close icon"></i>
+ <div class="header">
+ Set Group Locked Status
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Group ID</label>
+ <input v-model="groupId" type="text"
+ placeholder="[email protected]"
+ aria-label="Group ID">
+ </div>
+
+ <div class="field">
+ <label>Lock Status</label>
+ <div class="ui toggle checkbox">
+ <input type="checkbox" v-model="locked">
+ <label>{{ locked ? 'Lock group (only admins can edit group info)' : 'Unlock group (all members can edit group info)' }}</label>
+ </div>
+ <div class="ui info message" style="margin-top: 10px;">
+ <div class="header">What does this do?</div>
+ <ul class="list">
+ <li><strong>Locked:</strong> Only group admins can change group name, description, and photo</li>
+ <li><strong>Unlocked:</strong> All group members can change group info</li>
+ </ul>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
+ @click.prevent="handleSubmit" type="button">
+ {{ locked ? 'Lock Group' : 'Unlock Group' }}
+ <i :class="locked ? 'lock icon' : 'unlock icon'"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/components/GroupSetName.js b/src/views/components/GroupSetName.js
new file mode 100644
index 00000000..80f9f4ff
--- /dev/null
+++ b/src/views/components/GroupSetName.js
@@ -0,0 +1,102 @@
+export default {
+ name: 'GroupSetName',
+ data() {
+ return {
+ loading: false,
+ groupId: '',
+ name: '',
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalGroupSetName').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ return this.groupId.trim() !== '' && this.name.trim() !== '' && this.name.length <= 25;
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalGroupSetName').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ let response = await window.http.post(`/group/name`, {
+ group_id: this.groupId,
+ name: this.name
+ })
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.groupId = '';
+ this.name = '';
+ },
+ },
+ template: `
+ <div class="green card" @click="openModal" style="cursor: pointer">
+ <div class="content">
+ <a class="ui green right ribbon label">Group</a>
+ <div class="header">Set Group Name</div>
+ <div class="description">
+ Change the group name/title
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal Group Set Name -->
+ <div class="ui small modal" id="modalGroupSetName">
+ <i class="close icon"></i>
+ <div class="header">
+ Set Group Name
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Group ID</label>
+ <input v-model="groupId" type="text"
+ placeholder="[email protected]"
+ aria-label="Group ID">
+ </div>
+
+ <div class="field">
+ <label>Group Name</label>
+ <input v-model="name" type="text"
+ placeholder="Enter new group name..."
+ maxlength="25"
+ aria-label="Group Name">
+ <small class="text">Maximum 25 characters. Current length: {{ name.length }}/25</small>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
+ @click.prevent="handleSubmit" type="button">
+ Update Name
+ <i class="edit icon"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/components/GroupSetPhoto.js b/src/views/components/GroupSetPhoto.js
new file mode 100644
index 00000000..2a96776b
--- /dev/null
+++ b/src/views/components/GroupSetPhoto.js
@@ -0,0 +1,144 @@
+export default {
+ name: 'GroupSetPhoto',
+ data() {
+ return {
+ loading: false,
+ groupId: '',
+ photo: null,
+ photoFile: null,
+ previewUrl: null,
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalGroupSetPhoto').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ return this.groupId.trim() !== '';
+ },
+ handleFileChange(event) {
+ const file = event.target.files[0];
+ if (file) {
+ this.photoFile = file;
+ // Create preview
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ this.previewUrl = e.target.result;
+ };
+ reader.readAsDataURL(file);
+ }
+ },
+ handleRemovePhoto() {
+ this.photoFile = null;
+ this.previewUrl = null;
+ // Reset file input
+ const fileInput = document.querySelector('#photoUpload');
+ if (fileInput) {
+ fileInput.value = '';
+ }
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalGroupSetPhoto').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ const formData = new FormData();
+ formData.append('group_id', this.groupId);
+ if (this.photoFile) {
+ formData.append('photo', this.photoFile);
+ }
+
+ let response = await window.http.post(`/group/photo`, formData, {
+ headers: {
+ 'Content-Type': 'multipart/form-data'
+ }
+ })
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.groupId = '';
+ this.photoFile = null;
+ this.previewUrl = null;
+ const fileInput = document.querySelector('#photoUpload');
+ if (fileInput) {
+ fileInput.value = '';
+ }
+ },
+ },
+ template: `
+ <div class="green card" @click="openModal" style="cursor: pointer">
+ <div class="content">
+ <a class="ui green right ribbon label">Group</a>
+ <div class="header">Set Group Photo</div>
+ <div class="description">
+ Update or remove group profile picture
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal Group Set Photo -->
+ <div class="ui small modal" id="modalGroupSetPhoto">
+ <i class="close icon"></i>
+ <div class="header">
+ Set Group Photo
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Group ID</label>
+ <input v-model="groupId" type="text"
+ placeholder="[email protected]"
+ aria-label="Group ID">
+ </div>
+
+ <div class="field">
+ <label>Group Photo</label>
+ <input type="file" id="photoUpload" accept="image/*" @change="handleFileChange">
+ <small class="text">Select a JPEG image for best results. Leave empty to remove current photo.</small>
+ </div>
+
+ <div class="field" v-if="previewUrl">
+ <label>Preview</label>
+ <div style="display: flex; align-items: center; gap: 10px;">
+ <img :src="previewUrl" alt="Preview" style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px;">
+ <button class="ui red button" @click="handleRemovePhoto" type="button">
+ <i class="trash icon"></i> Remove
+ </button>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
+ @click.prevent="handleSubmit" type="button">
+ Update Photo
+ <i class="camera icon"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/components/GroupSetTopic.js b/src/views/components/GroupSetTopic.js
new file mode 100644
index 00000000..a01c1452
--- /dev/null
+++ b/src/views/components/GroupSetTopic.js
@@ -0,0 +1,103 @@
+export default {
+ name: 'GroupSetTopic',
+ data() {
+ return {
+ loading: false,
+ groupId: '',
+ topic: '',
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalGroupSetTopic').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isValidForm() {
+ return this.groupId.trim() !== '';
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalGroupSetTopic').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ let response = await window.http.post(`/group/topic`, {
+ group_id: this.groupId,
+ topic: this.topic
+ })
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.groupId = '';
+ this.topic = '';
+ },
+ },
+ template: `
+ <div class="green card" @click="openModal" style="cursor: pointer">
+ <div class="content">
+ <a class="ui green right ribbon label">Group</a>
+ <div class="header">Set Group Topic</div>
+ <div class="description">
+ Set or remove group description/topic
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal Group Set Topic -->
+ <div class="ui small modal" id="modalGroupSetTopic">
+ <i class="close icon"></i>
+ <div class="header">
+ Set Group Topic
+ </div>
+ <div class="content">
+ <form class="ui form">
+ <div class="field">
+ <label>Group ID</label>
+ <input v-model="groupId" type="text"
+ placeholder="[email protected]"
+ aria-label="Group ID">
+ </div>
+
+ <div class="field">
+ <label>Group Topic (Description)</label>
+ <textarea v-model="topic"
+ placeholder="Enter group description/topic... Leave empty to remove topic."
+ rows="4"
+ aria-label="Group Topic">
+ </textarea>
+ <small class="text">This will be displayed as the group description. Leave empty to remove the current topic.</small>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
+ @click.prevent="handleSubmit" type="button">
+ {{ topic.trim() === '' ? 'Remove Topic' : 'Update Topic' }}
+ <i :class="topic.trim() === '' ? 'trash icon' : 'edit icon'"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/index.html b/src/views/index.html
index 320e7116..b846045d 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -103,6 +103,11 @@
<group-create></group-create>
<group-join-with-link></group-join-with-link>
<group-add-participants></group-add-participants>
+ <group-set-photo></group-set-photo>
+ <group-set-name></group-set-name>
+ <group-set-locked></group-set-locked>
+ <group-set-announce></group-set-announce>
+ <group-set-topic></group-set-topic>
</div>
<div class="ui horizontal divider">
@@ -183,6 +188,11 @@
import GroupCreate from "./components/GroupCreate.js";
import GroupJoinWithLink from "./components/GroupJoinWithLink.js";
import GroupAddParticipants from "./components/GroupManageParticipants.js";
+ import GroupSetPhoto from "./components/GroupSetPhoto.js";
+ import GroupSetName from "./components/GroupSetName.js";
+ import GroupSetLocked from "./components/GroupSetLocked.js";
+ import GroupSetAnnounce from "./components/GroupSetAnnounce.js";
+ import GroupSetTopic from "./components/GroupSetTopic.js";
import NewsletterList from "./components/NewsletterList.js";
import AccountAvatar from "./components/AccountAvatar.js";
import AccountChangeAvatar from "./components/AccountChangeAvatar.js";
@@ -227,7 +237,7 @@
AppLogin, AppLoginWithCode, AppLogout, AppReconnect,
SendMessage, SendImage, SendFile, SendVideo, SendLink, SendContact, SendLocation, SendAudio, SendPoll, SendPresence,
MessageDelete, MessageUpdate, MessageReact, MessageRevoke,
- GroupList, GroupCreate, GroupJoinWithLink, GroupAddParticipants,
+ GroupList, GroupCreate, GroupJoinWithLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic,
NewsletterList,
AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck
},