89 lines
1.5 KiB
Go
89 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
)
|
|
|
|
func isWS(r *http.Request) bool {
|
|
return r.URL.Path == "/ws" || strings.HasPrefix(r.URL.Path, "/ws/")
|
|
}
|
|
|
|
func (s *S) serveWS(w http.ResponseWriter, r *http.Request) error {
|
|
ctx, can := context.WithCancel(r.Context())
|
|
defer can()
|
|
r = r.WithContext(ctx)
|
|
|
|
session := s.Session(ctx)
|
|
games, err := s.games.GamesForUser(ctx, session.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(games) == 0 {
|
|
return fmt.Errorf("user %s is in zero games", session.ID)
|
|
}
|
|
game := games[0]
|
|
|
|
c, err := websocket.Accept(w, r, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer c.CloseNow()
|
|
|
|
go func() {
|
|
defer can()
|
|
for {
|
|
_, b, err := c.Read(ctx)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
log.Printf("READ %s", b)
|
|
}
|
|
}()
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(time.Second * 1):
|
|
}
|
|
|
|
gameState, err := s.games.GameState(ctx, game)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if gameState.Started {
|
|
break
|
|
}
|
|
|
|
items := []map[string]any{}
|
|
for k := range gameState.Players {
|
|
name, err := s.games.UserName(ctx, k)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
items = append(items, map[string]any{"name": name})
|
|
}
|
|
msg := map[string]any{
|
|
"page": "A",
|
|
"items": items,
|
|
}
|
|
|
|
msgB, _ := json.Marshal(msg)
|
|
if err := c.Write(ctx, 1, msgB); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return fmt.Errorf("not impl: game started")
|
|
}
|