First pass at basic functionality.
This PR introduces the beginnings of Sprint Padawan. Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
+89
@@ -0,0 +1,89 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
if isLoggedIn(r) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "login.html", nil)
|
||||
return
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
|
||||
user, err := lib.GetUserByUsername(username)
|
||||
if err != nil || !lib.CheckPasswordHash(password, user.PasswordHash) {
|
||||
renderTemplate(w, "login.html", map[string]string{"Error": "Invalid credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, err := lib.CreateSession(user.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to create session", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session_token",
|
||||
Value: sessionID,
|
||||
Expires: time.Now().Add(24 * time.Hour),
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
if isLoggedIn(r) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "register.html", nil)
|
||||
return
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
confirm := r.FormValue("confirm_password")
|
||||
|
||||
if password != confirm {
|
||||
renderTemplate(w, "register.html", map[string]string{"Error": "Passwords do not match"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := lib.CreateUser(username, password); err != nil {
|
||||
renderTemplate(w, "register.html", map[string]string{"Error": "Username taken"})
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err == nil {
|
||||
if err := lib.DeleteSession(cookie.Value); err != nil {
|
||||
log.Printf("delete session error: %v", err)
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session_token",
|
||||
Value: "",
|
||||
Expires: time.Now().Add(-1 * time.Hour),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Path: "/",
|
||||
})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
type RoomView struct {
|
||||
ID int
|
||||
Name string
|
||||
Code string
|
||||
Scale string
|
||||
IsOwner bool
|
||||
MemberCount int
|
||||
}
|
||||
|
||||
func handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
rooms, err := lib.GetRoomSummariesForUser(user.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to load rooms", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
data := struct {
|
||||
*lib.User
|
||||
Rooms []RoomView
|
||||
}{
|
||||
User: user,
|
||||
}
|
||||
|
||||
for _, room := range rooms {
|
||||
data.Rooms = append(data.Rooms, RoomView{
|
||||
ID: room.ID,
|
||||
Name: room.Name,
|
||||
Code: room.Code,
|
||||
Scale: room.Scale,
|
||||
IsOwner: room.OwnerID == user.ID,
|
||||
MemberCount: room.MemberCount,
|
||||
})
|
||||
}
|
||||
|
||||
if err := templates.ExecuteTemplate(w, "index.html", data); err != nil {
|
||||
log.Printf("template error: %v", err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
func handleNewRoom(w http.ResponseWriter, r *http.Request) {
|
||||
if err := templates.ExecuteTemplate(w, "room_form.html", nil); err != nil {
|
||||
log.Printf("template error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleCreateRoom(w http.ResponseWriter, r *http.Request) {
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
name := r.FormValue("name")
|
||||
scale := r.FormValue("scale")
|
||||
room, err := lib.CreateRoom(name, user.ID, scale)
|
||||
if err != nil {
|
||||
log.Printf("create room error: %v", err)
|
||||
http.Error(w, "failed to create room", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", room.ID), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleJoinRoom(w http.ResponseWriter, r *http.Request) {
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
code := r.FormValue("code")
|
||||
room, err := lib.GetRoomByCode(code)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err := lib.AddUserToRoom(room.ID, user.ID); err != nil {
|
||||
http.Error(w, "failed to join room", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", room.ID), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleRoom(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := lib.AddUserToRoom(room.ID, user.ID); err != nil {
|
||||
http.Error(w, "failed to join room", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := buildRoomData(room, user)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to load room data", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "room.html", data)
|
||||
}
|
||||
|
||||
func handlePartialStories(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
renderRoomStories(w, roomID, user)
|
||||
}
|
||||
|
||||
func handlePartialMembers(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
renderRoomMembers(w, roomID, user)
|
||||
}
|
||||
|
||||
func handlePartialVoteArea(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if room.ActiveStoryID == nil {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
story, err := lib.GetStoryByID(*room.ActiveStoryID)
|
||||
if err != nil {
|
||||
http.Error(w, "story not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
roomData, err := buildRoomData(room, user)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to load room data", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
data := struct {
|
||||
RoomData RoomData
|
||||
Story lib.Story
|
||||
}{
|
||||
RoomData: roomData,
|
||||
Story: *story,
|
||||
}
|
||||
renderTemplate(w, "vote-area", data)
|
||||
}
|
||||
|
||||
func handleDeleteRoom(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if room.OwnerID != user.ID {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
err = lib.DeleteRoom(roomID)
|
||||
if err != nil {
|
||||
log.Printf("delete room error: %v", err)
|
||||
http.Error(w, "failed to delete room", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package api
|
||||
|
||||
import "net/http"
|
||||
|
||||
func SetupRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/login", handleLogin)
|
||||
mux.HandleFunc("/register", handleRegister)
|
||||
mux.HandleFunc("/logout", handleLogout)
|
||||
|
||||
mux.HandleFunc("/", requireAuth(handleIndex))
|
||||
mux.HandleFunc("/rooms/new", requireAuth(handleNewRoom))
|
||||
mux.HandleFunc("/rooms/create", requireAuth(handleCreateRoom))
|
||||
mux.HandleFunc("/rooms/join", requireAuth(handleJoinRoom))
|
||||
mux.HandleFunc("/rooms/{id}", requireAuth(handleRoom))
|
||||
mux.HandleFunc("/rooms/{id}/delete", requireAuth(handleDeleteRoom))
|
||||
|
||||
mux.HandleFunc("/rooms/{id}/partial/stories", requireAuth(handlePartialStories))
|
||||
mux.HandleFunc("/rooms/{id}/partial/members", requireAuth(handlePartialMembers))
|
||||
mux.HandleFunc("/rooms/{id}/partial/vote-area", requireAuth(handlePartialVoteArea))
|
||||
|
||||
mux.HandleFunc("/rooms/{id}/stories/new", requireAuth(handleNewStoryForm))
|
||||
mux.HandleFunc("/rooms/{id}/stories", requireAuth(handleAddStory))
|
||||
mux.HandleFunc("/rooms/{id}/active", requireAuth(handleSetActiveStory))
|
||||
mux.HandleFunc("/rooms/{id}/vote", requireAuth(handleVote))
|
||||
mux.HandleFunc("/rooms/{id}/reveal", requireAuth(handleReveal))
|
||||
mux.HandleFunc("/rooms/{id}/stories/{story_id}/edit", requireAuth(handleEditStoryForm))
|
||||
mux.HandleFunc("/rooms/{id}/stories/{story_id}/rename", requireAuth(handleRenameStory))
|
||||
mux.HandleFunc("/rooms/{id}/stories/{story_id}/delete", requireAuth(handleDeleteStory))
|
||||
mux.HandleFunc("/rooms/{id}/stories/{story_id}/reset", requireAuth(handleResetStory))
|
||||
mux.HandleFunc("/rooms/{id}/stories/{story_id}/unreveal", requireAuth(handleUnrevealStory))
|
||||
mux.HandleFunc("/sse/{room_id}", requireAuth(handleSSE))
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
func handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getPathInt(r, "room_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user, ok := r.Context().Value(userKey).(*lib.User)
|
||||
if !ok {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ch := make(chan string, 10)
|
||||
addSSEClient(roomID, user.ID, ch)
|
||||
broadcast(roomID, "members")
|
||||
|
||||
notify := r.Context().Done()
|
||||
heartbeat := time.NewTicker(25 * time.Second)
|
||||
defer heartbeat.Stop()
|
||||
|
||||
fmt.Fprint(w, ": connected\n\n")
|
||||
flusher.Flush()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-notify:
|
||||
removeSSEClient(roomID, ch)
|
||||
broadcast(roomID, "members")
|
||||
return
|
||||
case <-heartbeat.C:
|
||||
fmt.Fprint(w, ": keep-alive\n\n")
|
||||
flusher.Flush()
|
||||
case event := <-ch:
|
||||
fmt.Fprintf(w, "event: %s\ndata: true\n\n", event)
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
func handleNewStoryForm(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "story_form.html", room)
|
||||
}
|
||||
|
||||
func handleAddStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
title := r.FormValue("title")
|
||||
if _, err := lib.CreateStory(id, title); err != nil {
|
||||
log.Printf("create story error: %v", err)
|
||||
http.Error(w, "failed to create story", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "stories")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleSetActiveStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getFormInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := lib.SetActiveStory(id, sid); err != nil {
|
||||
http.Error(w, "failed to set active story", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
broadcast(id, "stories")
|
||||
broadcast(id, "members")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleResetStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getPathInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := lib.UnrevealStory(sid); err != nil {
|
||||
http.Error(w, "failed to reset story", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := lib.ClearVotesForStory(sid); err != nil {
|
||||
http.Error(w, "failed to clear votes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
broadcast(id, "stories")
|
||||
broadcast(id, "members")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleVote(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
value := r.FormValue("value")
|
||||
sid, err := getFormInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := lib.VoteOnStory(sid, user.ID, value); err != nil {
|
||||
http.Error(w, "failed to vote", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "members")
|
||||
story, storyErr := lib.GetStoryByID(sid)
|
||||
if storyErr == nil && story.Voted {
|
||||
broadcast(id, "stories")
|
||||
}
|
||||
|
||||
if isHTMX(r) {
|
||||
if storyErr != nil {
|
||||
http.Error(w, "story not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
room, err := lib.GetRoomByID(id)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
tmplData := struct {
|
||||
RoomID int
|
||||
Story lib.Story
|
||||
Scale string
|
||||
UserVote string
|
||||
}{
|
||||
RoomID: id,
|
||||
Story: *story,
|
||||
Scale: room.Scale,
|
||||
UserVote: value,
|
||||
}
|
||||
renderTemplate(w, "vote_form.html", tmplData)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleReveal(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getFormInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := lib.RevealVotes(sid); err != nil {
|
||||
http.Error(w, "failed to reveal votes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "stories")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleUnrevealStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getPathInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := lib.UnrevealStory(sid); err != nil {
|
||||
http.Error(w, "failed to hide votes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "stories")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleEditStoryForm(w http.ResponseWriter, r *http.Request) {
|
||||
roomID, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
storyID, err := getPathInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
story, err := lib.GetStoryByID(storyID)
|
||||
if err != nil {
|
||||
http.Error(w, "story not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
data := struct {
|
||||
RoomID int
|
||||
Story lib.Story
|
||||
}{
|
||||
RoomID: roomID,
|
||||
Story: *story,
|
||||
}
|
||||
renderTemplate(w, "story_edit.html", data)
|
||||
}
|
||||
|
||||
func handleRenameStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getPathInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
title := r.FormValue("title")
|
||||
if err := lib.RenameStory(sid, title); err != nil {
|
||||
http.Error(w, "failed to rename story", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "stories")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleDeleteStory(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := getRoomID(r)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid room id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user := r.Context().Value(userKey).(*lib.User)
|
||||
sid, err := getPathInt(r, "story_id")
|
||||
if err != nil {
|
||||
http.Error(w, "invalid story id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := lib.DeleteStory(sid); err != nil {
|
||||
http.Error(w, "failed to delete story", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
broadcast(id, "stories")
|
||||
if isHTMX(r) {
|
||||
renderRoomStories(w, id, user)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/rooms/%d", id), http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
var templates *template.Template
|
||||
|
||||
func InitTemplates(fsys fs.FS) {
|
||||
templates = template.Must(template.New("").Funcs(template.FuncMap{
|
||||
"scaleToOptions": scaleToOptions,
|
||||
"derefInt": func(i *int) int {
|
||||
if i == nil {
|
||||
return 0
|
||||
}
|
||||
return *i
|
||||
},
|
||||
"slice": func(s string, start, end int) string {
|
||||
if len(s) == 0 {
|
||||
return ""
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if end > len(s) || end <= 0 {
|
||||
end = len(s)
|
||||
}
|
||||
if start > end {
|
||||
return ""
|
||||
}
|
||||
return s[start:end]
|
||||
},
|
||||
"dict": func(values ...interface{}) (map[string]interface{}, error) {
|
||||
if len(values)%2 != 0 {
|
||||
return nil, fmt.Errorf("odd number of arguments to dict")
|
||||
}
|
||||
d := make(map[string]interface{})
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("dict keys must be strings")
|
||||
}
|
||||
d[key] = values[i+1]
|
||||
}
|
||||
return d, nil
|
||||
},
|
||||
}).ParseFS(fsys, "templates/*.html"))
|
||||
}
|
||||
|
||||
func isHTMX(r *http.Request) bool {
|
||||
return r.Header.Get("HX-Request") == "true"
|
||||
}
|
||||
|
||||
func renderTemplate(w http.ResponseWriter, name string, data interface{}) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := templates.ExecuteTemplate(w, name, data); err != nil {
|
||||
log.Printf("template error (%s): %v", name, err)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func renderRoomStories(w http.ResponseWriter, roomID int, user *lib.User) {
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
data, err := buildRoomData(room, user)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to load room data", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "stories-panel", data)
|
||||
}
|
||||
|
||||
func renderRoomMembers(w http.ResponseWriter, roomID int, user *lib.User) {
|
||||
room, err := lib.GetRoomByID(roomID)
|
||||
if err != nil {
|
||||
http.Error(w, "room not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
data, err := buildRoomData(room, user)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to load room data", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "members-panel", data)
|
||||
}
|
||||
|
||||
func requireAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
user, err := lib.GetUserFromSession(cookie.Value)
|
||||
if err != nil || user == nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userKey, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func isLoggedIn(r *http.Request) bool {
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
user, err := lib.GetUserFromSession(cookie.Value)
|
||||
return err == nil && user != nil
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userKey contextKey = "user"
|
||||
|
||||
type sseClient struct {
|
||||
ch chan string
|
||||
userID int
|
||||
}
|
||||
|
||||
type MemberView struct {
|
||||
Username string
|
||||
HasVoted bool
|
||||
ID int
|
||||
}
|
||||
|
||||
type RoomData struct {
|
||||
*lib.Room
|
||||
User *lib.User
|
||||
Members []MemberView
|
||||
Stories []lib.Story
|
||||
IsOwner bool
|
||||
UserVotes map[int]string
|
||||
StoryVotes map[int][]lib.VoteView
|
||||
}
|
||||
|
||||
var (
|
||||
roomClients = make(map[int][]*sseClient)
|
||||
clientsMu sync.RWMutex
|
||||
)
|
||||
|
||||
func addSSEClient(roomID, userID int, ch chan string) {
|
||||
clientsMu.Lock()
|
||||
defer clientsMu.Unlock()
|
||||
roomClients[roomID] = append(roomClients[roomID], &sseClient{ch: ch, userID: userID})
|
||||
}
|
||||
|
||||
func removeSSEClient(roomID int, ch chan string) {
|
||||
clientsMu.Lock()
|
||||
defer clientsMu.Unlock()
|
||||
clients := roomClients[roomID]
|
||||
for i, c := range clients {
|
||||
if c.ch == ch {
|
||||
roomClients[roomID] = append(clients[:i], clients[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(roomClients[roomID]) == 0 {
|
||||
delete(roomClients, roomID)
|
||||
}
|
||||
}
|
||||
|
||||
func broadcast(roomID int, event string) {
|
||||
clientsMu.RLock()
|
||||
snapshot := append([]*sseClient(nil), roomClients[roomID]...)
|
||||
clientsMu.RUnlock()
|
||||
|
||||
if len(snapshot) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
deadSet := make(map[*sseClient]struct{})
|
||||
for _, c := range snapshot {
|
||||
select {
|
||||
case c.ch <- event:
|
||||
default:
|
||||
deadSet[c] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if len(deadSet) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
clientsMu.Lock()
|
||||
defer clientsMu.Unlock()
|
||||
|
||||
current := roomClients[roomID]
|
||||
alive := current[:0]
|
||||
for _, c := range current {
|
||||
if _, dead := deadSet[c]; dead {
|
||||
continue
|
||||
}
|
||||
alive = append(alive, c)
|
||||
}
|
||||
if len(alive) == 0 {
|
||||
delete(roomClients, roomID)
|
||||
return
|
||||
}
|
||||
roomClients[roomID] = alive
|
||||
}
|
||||
|
||||
func GetConnectedUserIDs(roomID int) []int {
|
||||
clientsMu.RLock()
|
||||
defer clientsMu.RUnlock()
|
||||
seen := make(map[int]bool)
|
||||
var ids []int
|
||||
for _, c := range roomClients[roomID] {
|
||||
if !seen[c.userID] {
|
||||
seen[c.userID] = true
|
||||
ids = append(ids, c.userID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func scaleToOptions(scale string) []string {
|
||||
switch scale {
|
||||
case "fibonacci":
|
||||
return []string{"1", "2", "3", "5", "8", "13", "21", "?"}
|
||||
case "tshirt":
|
||||
return []string{"XS", "S", "M", "L", "XL", "XXL", "?"}
|
||||
case "linear":
|
||||
return []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "?"}
|
||||
default:
|
||||
return []string{"1", "2", "3", "5", "8", "13", "21", "?"}
|
||||
}
|
||||
}
|
||||
|
||||
func getRoomID(r *http.Request) (int, error) {
|
||||
return getPathInt(r, "id")
|
||||
}
|
||||
|
||||
func getPathInt(r *http.Request, key string) (int, error) {
|
||||
raw := r.PathValue(key)
|
||||
if raw == "" {
|
||||
return 0, errors.New("missing path parameter")
|
||||
}
|
||||
id, err := strconv.Atoi(raw)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, errors.New("invalid path parameter")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func getFormInt(r *http.Request, key string) (int, error) {
|
||||
raw := r.FormValue(key)
|
||||
if raw == "" {
|
||||
return 0, errors.New("missing form value")
|
||||
}
|
||||
id, err := strconv.Atoi(raw)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, errors.New("invalid form value")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func buildRoomData(room *lib.Room, user *lib.User) (RoomData, error) {
|
||||
members, err := lib.GetRoomMembers(room.ID)
|
||||
if err != nil {
|
||||
return RoomData{}, err
|
||||
}
|
||||
|
||||
stories, err := lib.GetStoriesForRoom(room.ID)
|
||||
if err != nil {
|
||||
return RoomData{}, err
|
||||
}
|
||||
|
||||
connectedIDs := GetConnectedUserIDs(room.ID)
|
||||
connectedMap := make(map[int]bool)
|
||||
for _, cid := range connectedIDs {
|
||||
connectedMap[cid] = true
|
||||
}
|
||||
connectedMap[user.ID] = true
|
||||
|
||||
storyIDs := make([]int, 0, len(stories))
|
||||
revealedStoryIDs := make([]int, 0, len(stories))
|
||||
for _, s := range stories {
|
||||
storyIDs = append(storyIDs, s.ID)
|
||||
if s.Voted {
|
||||
revealedStoryIDs = append(revealedStoryIDs, s.ID)
|
||||
}
|
||||
}
|
||||
|
||||
votesByStory, err := lib.GetVotesForStories(storyIDs)
|
||||
if err != nil {
|
||||
return RoomData{}, err
|
||||
}
|
||||
|
||||
storyVotes, err := lib.GetVoteViewsForStories(revealedStoryIDs)
|
||||
if err != nil {
|
||||
return RoomData{}, err
|
||||
}
|
||||
|
||||
activeVotesByUser := make(map[int]bool)
|
||||
if room.ActiveStoryID != nil {
|
||||
for _, v := range votesByStory[*room.ActiveStoryID] {
|
||||
activeVotesByUser[v.UserID] = true
|
||||
}
|
||||
}
|
||||
|
||||
var memberViews []MemberView
|
||||
for _, m := range members {
|
||||
if !connectedMap[m.ID] {
|
||||
continue
|
||||
}
|
||||
hasVoted := activeVotesByUser[m.ID]
|
||||
memberViews = append(memberViews, MemberView{
|
||||
Username: m.Username,
|
||||
HasVoted: hasVoted,
|
||||
ID: m.ID,
|
||||
})
|
||||
}
|
||||
|
||||
userVotes := make(map[int]string)
|
||||
for _, s := range stories {
|
||||
for _, v := range votesByStory[s.ID] {
|
||||
if v.UserID == user.ID {
|
||||
userVotes[s.ID] = v.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return RoomData{
|
||||
Room: room,
|
||||
User: user,
|
||||
Members: memberViews,
|
||||
Stories: stories,
|
||||
IsOwner: room.OwnerID == user.ID,
|
||||
UserVotes: userVotes,
|
||||
StoryVotes: storyVotes,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user