77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/websocket/v2"
|
|
)
|
|
|
|
func (h *Handler) ConnectSocket(c *fiber.Ctx) error {
|
|
if !websocket.IsWebSocketUpgrade(c) {
|
|
h.logger.Warn("WebSocket upgrade required")
|
|
return fiber.ErrUpgradeRequired
|
|
}
|
|
|
|
userID, ok := c.Locals("userID").(int64)
|
|
if !ok || userID == 0 {
|
|
h.logger.Error("Invalid user ID in context")
|
|
return fiber.NewError(fiber.StatusUnauthorized, "invalid user identification")
|
|
}
|
|
|
|
c.Locals("allowed", true)
|
|
|
|
return websocket.New(func(conn *websocket.Conn) {
|
|
ctx := context.Background()
|
|
logger := h.logger.With("userID", userID, "remoteAddr", conn.RemoteAddr())
|
|
|
|
if err := h.notificationSvc.ConnectWebSocket(ctx, userID, conn); err != nil {
|
|
logger.Error("Failed to connect WebSocket", "error", err)
|
|
_ = conn.Close()
|
|
return
|
|
}
|
|
|
|
logger.Info("WebSocket connection established")
|
|
|
|
defer func() {
|
|
h.notificationSvc.DisconnectWebSocket(userID)
|
|
logger.Info("WebSocket connection closed")
|
|
_ = conn.Close()
|
|
}()
|
|
|
|
for {
|
|
if _, _, err := conn.ReadMessage(); err != nil {
|
|
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
|
logger.Warn("WebSocket unexpected close", "error", err)
|
|
}
|
|
break
|
|
}
|
|
}
|
|
})(c)
|
|
}
|
|
|
|
func (h *Handler) MarkNotificationAsRead(c *fiber.Ctx) error {
|
|
type Request struct {
|
|
NotificationID string `json:"notification_id" validate:"required"`
|
|
}
|
|
|
|
var req Request
|
|
if err := c.BodyParser(&req); err != nil {
|
|
h.logger.Error("Failed to parse request body", "error", err)
|
|
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
|
}
|
|
|
|
userID, ok := c.Locals("userID").(int64)
|
|
if !ok || userID == 0 {
|
|
h.logger.Error("Invalid user ID in context")
|
|
return fiber.NewError(fiber.StatusUnauthorized, "invalid user identification")
|
|
}
|
|
|
|
if err := h.notificationSvc.MarkAsRead(context.Background(), req.NotificationID, userID); err != nil {
|
|
h.logger.Error("Failed to mark notification as read", "notificationID", req.NotificationID, "error", err)
|
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update notification status")
|
|
}
|
|
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Notification marked as read"})
|
|
}
|