some-automoderation/routes/room_page.go

105 lines
2.6 KiB
Go

package routes
import (
"embed"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"time"
"sunshine.industries/some-automoderation/rooms"
"sunshine.industries/some-automoderation/sessions"
)
const roomPath = "/room/"
// registering all routes for page and logic of /room/:roomName
func registerPageRoutes(
templateFs *embed.FS,
sessionSM sessions.SessionManagement,
roomsM rooms.RoomManager,
) {
http.HandleFunc("/rooms/random", streamingBsRoute())
http.Handle(roomPath,
authedPageMiddleware(
sessionSM,
http.StripPrefix(roomPath, roomPageRoute(templateFs, roomsM))))
}
func streamingBsRoute() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "text/event-stream")
startTime, endTime := 0, 0
for {
select {
case <-r.Context().Done():
log.Printf("canlecced streaming!")
return
default:
log.Printf("another step in streaming bs")
data := "data: <div>hello with data %d! waited %d</div> \n\n"
startTime = time.Now().Nanosecond()
diff := endTime - startTime
fmt.Fprintf(w, data, rand.Intn(100), diff)
w.(http.Flusher).Flush()
time.Sleep(3 * time.Second)
endTime = time.Now().Nanosecond()
}
}
}
}
func roomPageRoute(
templateFs *embed.FS,
roomsM rooms.RoomManager,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
roomName := r.URL.Path
if roomName == "" {
log.Printf("access to empty room")
// TODO return error i suppose
w.Header().Add("HX-Redirect", "/")
return
}
// check session,
session, found := getContextSession(r.Context())
if !found {
log.Printf("session not found %t", found)
// TODO here will be rendering of
// 'create this room' or 'join this room'
// but yeah, let's just use auth middle that redirects to /
w.Header().Add("HX-Redirect", "/")
return
}
if session.RoomId != roomName {
log.Printf("session found %+v, but for wrong room, trying to access %s", session, roomName)
w.Header().Add("HX-Redirect", "/")
return
}
// now we should have a session for this specific room
fmt.Printf("all checks for room %s passed with %+v", roomName, session)
templFile := "templates/room.gohtml"
tmpl := template.Must(template.ParseFS(templateFs, templFile))
pageData := struct {
RoomName string
}{
RoomName: roomName,
}
err := tmpl.Execute(w, pageData)
if err != nil {
log.Printf("/room/%s my error in executing template, huh\n %s", roomName, err)
}
}
}