radiodiodio/www/www.go
2019-01-04 09:59:01 +01:00

152 lines
3.0 KiB
Go

package www
import (
"log"
"strconv"
"sync"
"html/template"
"net/http"
"github.com/gorilla/websocket"
"../playlist"
)
// todo: hub - https://stackoverflow.com/questions/31532652/go-websocket-send-all-clients-a-message
var wsc *websocket.Conn
var p *playlist.Playlist
var pp *playlist.PrettyPlaylist
var mp *playlist.MinimalPlaylist
var bundle *Bundle
var mutex = &sync.Mutex{}
var pln = log.Println
type op_t struct {
OP string `json:"op"`
ID string `json:"id"`
INDEX int `json:"index"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 512,
WriteBufferSize: 1024,
}
func Init(playlist *playlist.Playlist) {
p = playlist
p.CALLB = pop_callback
pp = p.Pretty()
mp = p.Minimal()
bundle = makeBundle()
go bundle.process()
http.HandleFunc("/pp", pp_handler)
http.HandleFunc("/ppop", pp_operations)
}
func pp_handler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("./www/tmpl/playlist.html")
if err != nil {
pln(err)
return
}
pp.Print()
t.Execute(w, pp)
}
func pp_operations(w http.ResponseWriter, r *http.Request) {
pln("new connection")
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
pln(err)
return
}
// pln("GGGG")
// s := &Socket{wsc: c, send: make(chan []byte, 1024), bundle: bundle}
// s.bundle.add <- s
s := makeSocket(c, bundle)
go s.read()
go s.write()
// // this should be hub
// go readop(c)
}
func (s *Socket) read() {
defer s.close()
for {
opdata := &op_t{}
if err := s.wsc.ReadJSON(&opdata); err != nil {
pln("0")
// if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
pln("connection closed - read")
break
// }
}
if opdata.OP == "move" {
if id, err := strconv.ParseUint(opdata.ID, 10, 32); err == nil {
mutex.Lock()
p.Move(uint32(id), opdata.INDEX)
pp = p.Pretty()
mp = p.Minimal()
mutex.Unlock()
s.bundle.broadcast <- mp.Encode() /// crap this nees to be []byte
}
}
}
}
func (s *Socket) write() {
for {
select {
case mp, _ := <-s.send:
w, err := s.wsc.NextWriter(websocket.TextMessage);
if err != nil {
// if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
pln("connection closed - write")
return
// }
}
w.Write(mp)
// is there queued messages?
w.Close()
}
}
}
func pop_callback(list *playlist.Playlist) {
if list == p {
pp = p.Pretty()
mp = p.Minimal()
bundle.broadcast <- mp.Encode()
}
}
// func readop(c *websocket.Conn) {
// for {
// opdata := &op_t{}
// if err := c.ReadJSON(&opdata); err != nil {
// pln(err)
// return //connection lost?
// }
// if opdata.OP == "move" {
// if id, err := strconv.ParseUint(opdata.ID, 10, 32); err == nil {
// p.Move(uint32(id), opdata.INDEX)
// pp = p.Pretty()
// mp = p.Minimal()
// // pp.Print()
// }
// }
// if err := c.WriteJSON(mp); err != nil {
// pln(err)
// return //connection lost?
// }
// }
// }