audon/room.go

82 wiersze
2.1 KiB
Go
Czysty Zwykły widok Historia

2022-12-03 03:20:49 +00:00
package main
import (
"net/http"
"time"
"github.com/jaevor/go-nanoid"
"github.com/labstack/echo/v4"
"github.com/livekit/protocol/auth"
"go.mongodb.org/mongo-driver/mongo"
)
func createRoomHandler(c echo.Context) (err error) {
room := new(Room)
if err = c.Bind(room); err != nil {
return ErrInvalidRequestFormat
}
2022-12-04 05:19:41 +00:00
if err = mainValidator.StructExcept(room, "RoomID"); err != nil { // New RoomID will be created, so one in request doesn't matter
2022-12-03 03:20:49 +00:00
return wrapValidationError(err)
}
canonic, err := nanoid.Standard(16)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
room.RoomID = canonic()
sess, err := getSession(c)
if err != nil {
c.Logger().Error(err)
return ErrSessionNotAvailable
}
sessData, err := getSessionData(sess)
if err != nil {
return ErrInvalidCookie
}
var host *AudonUser
host, err = findUserByID(c.Request().Context(), sessData.AudonID)
if err == mongo.ErrNoDocuments {
return c.JSON(http.StatusNotFound, []string{sessData.AudonID})
} else if err != nil {
c.Logger().Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
room.Host = host
2022-12-04 17:52:44 +00:00
now := time.Now().UTC()
if now.Sub(room.ScheduledAt) > 0 {
room.ScheduledAt = now
}
2022-12-04 05:19:41 +00:00
// If CoHosts are already registered, retrieve their AudonID
for i, cohost := range room.CoHost {
2022-12-03 03:20:49 +00:00
cohostUser, err := findUserByRemote(c.Request().Context(), cohost.RemoteID, cohost.RemoteURL)
if err == nil {
2022-12-04 17:52:44 +00:00
room.CoHost[i] = cohostUser
2022-12-03 03:20:49 +00:00
}
}
2022-12-04 05:19:41 +00:00
2022-12-04 17:52:44 +00:00
room.CreatedAt = now
coll := mainDB.Collection(COLLECTION_ROOM)
if _, insertErr := coll.InsertOne(c.Request().Context(), room); insertErr != nil {
c.Logger().Error(insertErr)
2022-12-04 05:19:41 +00:00
return echo.NewHTTPError(http.StatusInternalServerError)
}
2022-12-04 17:52:44 +00:00
return c.String(http.StatusCreated, room.RoomID)
2022-12-03 03:20:49 +00:00
}
2022-12-04 17:52:44 +00:00
func getHostToken(room *Room) (string, error) {
2022-12-04 05:19:41 +00:00
at := auth.NewAccessToken(mainConfig.Livekit.APIKey, mainConfig.Livekit.APISecret)
2022-12-03 03:20:49 +00:00
grant := &auth.VideoGrant{
2022-12-04 17:52:44 +00:00
Room: room.RoomID,
RoomJoin: true,
2022-12-03 03:20:49 +00:00
}
2022-12-04 17:52:44 +00:00
at.AddGrant(grant).SetIdentity(room.Host.AudonID).SetValidFor(10 * time.Minute)
2022-12-03 03:20:49 +00:00
return at.ToJWT()
}