113 lines
2.1 KiB
Go
113 lines
2.1 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.tek.govt.hu/dowerx/chat/server/model"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
const CHANNEL_ID string = "id"
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
}
|
|
|
|
func listAvailableChannels(c *gin.Context) {
|
|
token, _ := c.Get(SESSION_COOKIE)
|
|
|
|
channels, err := chatController.ListAvailableChannels(token.(string))
|
|
if err != nil {
|
|
sendError(c, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "channels listed",
|
|
"channels": channels,
|
|
})
|
|
}
|
|
|
|
func getMessages(c *gin.Context) {
|
|
id, err := strconv.Atoi(c.Param(CHANNEL_ID))
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": "invalid channel id",
|
|
})
|
|
return
|
|
}
|
|
|
|
messages, msgErr := chatController.GetMessages(id)
|
|
if msgErr != nil {
|
|
sendError(c, msgErr)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "messages listed",
|
|
"messages": messages,
|
|
})
|
|
}
|
|
|
|
func sendMessage(c *gin.Context) {
|
|
token, _ := c.Get(SESSION_COOKIE)
|
|
|
|
message := model.Message{}
|
|
if err := c.Bind(&message); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
err := chatController.SendMessage(token.(string), message.Channel, message.Content)
|
|
if err != nil {
|
|
fmt.Println(err.Error())
|
|
|
|
sendError(c, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "message sent",
|
|
})
|
|
}
|
|
|
|
func subscribeToChannel(c *gin.Context) {
|
|
// TODO: check if the user has right to subscribe to the given channel
|
|
id, err := strconv.Atoi(c.Param(CHANNEL_ID))
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": "invalid channel id",
|
|
})
|
|
return
|
|
}
|
|
|
|
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
|
if err != nil {
|
|
fmt.Println(err.Error())
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
messages, chanErr := chatController.SubscribeToChannel(c, id)
|
|
|
|
for {
|
|
select {
|
|
case msg := <-messages:
|
|
if err := conn.WriteJSON(msg); err != nil {
|
|
return
|
|
}
|
|
|
|
case err := <-chanErr:
|
|
fmt.Println(err.Error())
|
|
return
|
|
}
|
|
}
|
|
}
|