-
Notifications
You must be signed in to change notification settings - Fork 33
/
messages.go
117 lines (94 loc) · 2.57 KB
/
messages.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"encoding/json"
"net/http"
"github.com/cryptag/leapchat/miniware"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
type Message []byte
type OutgoingPayload struct {
Ephemeral []Message `json:"ephemeral"`
FromServer FromServer `json:"from_server,omitempty"`
}
type FromServer struct {
AllMessagesDeleted bool `json:"all_messages_deleted,omitempty"`
}
type ToServer struct {
TTL *int `json:"ttl_secs"`
DeleteAllMessages bool `json:"delete_all_messages"`
}
type IncomingPayload struct {
Ephemeral []Message `json:"ephemeral"`
ToServer ToServer `json:"to_server"`
}
func WSMessagesHandler(rooms *RoomManager) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Both guaranteed by middleware
wsConn, _ := miniware.GetWebsocketConn(r)
roomID, _ := miniware.GetMinilockID(r)
room := rooms.GetRoom(roomID)
client := &Client{
wsConn: wsConn,
room: room,
}
room.AddClient(client)
go messageReader(room, client)
}
}
func messageReader(room *Room, client *Client) {
msgs, err := room.GetMessages()
if err != nil {
client.SendError(err.Error(), err)
return
}
// Send them already-existing messages
err = client.SendMessages(msgs...)
if err != nil {
client.SendError(err.Error(), err)
return
}
for {
messageType, p, err := client.wsConn.ReadMessage()
if err != nil {
// TODO: Consider adding more checks
log.Debugf("Error reading ws message: %s", err)
room.RemoveClient(client)
return
}
// Respond to message depending on message type
switch messageType {
case websocket.TextMessage:
var payload IncomingPayload
err := json.Unmarshal(p, &payload)
if err != nil {
log.Debugf("Error unmarshalling message `%s` -- %s", p, err)
continue
}
if payload.ToServer.DeleteAllMessages {
err = room.DeleteAllMessages()
if err != nil {
room.BroadcastMessages(client, Message(err.Error()))
log.Errorf("Error deleting all messages from room %s -- %s", room.ID, err)
continue
}
room.BroadcastDeleteSignal()
continue
}
err = room.AddMessages(payload.Ephemeral, payload.ToServer.TTL)
if err != nil {
log.Debugf("Error from AddMessages: %v", err)
continue
}
room.BroadcastMessages(client, payload.Ephemeral...)
case websocket.BinaryMessage:
log.Debug("Binary messages are unsupported")
case websocket.CloseMessage:
log.Debug("Got close message")
room.RemoveClient(client)
return
default:
log.Debugf("Unsupport messageType: %d", messageType)
}
}
}