From 66d7cd7193217037620e401fea10fbe6f9cc08bc Mon Sep 17 00:00:00 2001 From: Denis Arh Date: Sun, 29 Jul 2018 01:06:36 +0200 Subject: [PATCH] Add connected/disconnected messages --- sam/websocket/outgoing/connection.go | 25 +++++++++++++++++++++++++ sam/websocket/outgoing/payload.go | 3 +++ sam/websocket/websocket.go | 8 +++++++- 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 sam/websocket/outgoing/connection.go diff --git a/sam/websocket/outgoing/connection.go b/sam/websocket/outgoing/connection.go new file mode 100644 index 000000000..6a4f86634 --- /dev/null +++ b/sam/websocket/outgoing/connection.go @@ -0,0 +1,25 @@ +package outgoing + +import ( + "encoding/json" +) + +type ( + Connected struct { + // Who did connect? + UserID string `json:"uid"` + } + + Disconnected struct { + // Who did disconnect? + UserID string `json:"uid"` + } +) + +func (p *Connected) EncodeMessage() ([]byte, error) { + return json.Marshal(Payload{Connected: p}) +} + +func (p *Disconnected) EncodeMessage() ([]byte, error) { + return json.Marshal(Payload{Disconnected: p}) +} diff --git a/sam/websocket/outgoing/payload.go b/sam/websocket/outgoing/payload.go index 2b459a599..901790ed8 100644 --- a/sam/websocket/outgoing/payload.go +++ b/sam/websocket/outgoing/payload.go @@ -4,6 +4,9 @@ type ( Payload struct { *Error `json:"error,omitempty"` + *Connected `json:"conn,omitempty"` + *Disconnected `json:"disc,omitempty"` + *Message `json:"m,omitempty"` *MessageDelete `json:"md,omitempty"` *MessageUpdate `json:"mu,omitempty"` diff --git a/sam/websocket/websocket.go b/sam/websocket/websocket.go index 4d1af76ba..ab2bf0100 100644 --- a/sam/websocket/websocket.go +++ b/sam/websocket/websocket.go @@ -6,6 +6,7 @@ import ( "context" "github.com/crusttech/crust/auth" "github.com/crusttech/crust/sam/types" + "github.com/crusttech/crust/sam/websocket/outgoing" "github.com/gorilla/websocket" "github.com/pkg/errors" "github.com/titpetric/factory/resputil" @@ -42,7 +43,8 @@ func (ws Websocket) Open(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Disallow all unauthorized! - if !auth.GetIdentityFromContext(ctx).Valid() { + identity := auth.GetIdentityFromContext(ctx) + if !identity.Valid() { resputil.JSON(w, errors.New("Unauthorized")) return } @@ -60,7 +62,11 @@ func (ws Websocket) Open(w http.ResponseWriter, r *http.Request) { session := store.Save(Session{}.New(r.Context(), conn)) + session.sendToAll(&outgoing.Connected{UserID: uint64toa(identity.GetID())}) + if err := session.Handle(); err != nil { // @todo: log error, because at this point we can't really write it to w } + + session.sendToAll(&outgoing.Disconnected{UserID: uint64toa(identity.GetID())}) }