-
Notifications
You must be signed in to change notification settings - Fork 16
/
philote.go
91 lines (73 loc) · 1.97 KB
/
philote.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
package main
import (
log "github.com/sirupsen/logrus"
"github.com/gorilla/websocket"
"github.com/satori/go.uuid"
)
type Philote struct {
ID string
AccessKey *AccessKey
Hive *hive
ws *websocket.Conn
IncomingMessages chan *Message
}
func NewPhilote(ak *AccessKey, ws *websocket.Conn) (*Philote) {
p := &Philote{
ws: ws,
ID: uuid.NewV4().String(),
AccessKey: ak,
IncomingMessages: make(chan *Message),
}
go p.DistributeIncomingMessages()
return p
}
func (p *Philote) DistributeIncomingMessages() {
var message *Message
for {
message = <- p.IncomingMessages
p.ws.WriteJSON(message)
}
}
func (p *Philote) Listen() {
log.WithFields(log.Fields{"philote": p.ID}).Debug("Listening to Philote")
for {
message := &Message{}
err := p.ws.ReadJSON(&message); if err != nil {
log.WithFields(log.Fields{
"philote": p.ID,
"error": err.Error()}).Warn("Error reading from socket, disconnecting")
p.Hive.Disconnect <- p
break
}
// Ensure no tampering with message data
message.IssuerID = p.ID
log.WithFields(log.Fields{"philote": p.ID, "channel": message.Channel}).Debug("Received message from socket")
if p.AccessKey.CanWrite(message.Channel) {
go p.publish(message)
} else {
log.WithFields(log.Fields{
"philote": p.ID,
"channel": message.Channel,
"data": message.Data,
}).Info("Message dropped due to insufficient write permissions")
}
}
}
func (p *Philote) disconnect() {
log.WithFields(log.Fields{"philote": p.ID}).Debug("Closing Philote")
p.ws.Close()
}
func (p *Philote) publish(message *Message) {
message.IssuerID = p.ID
for _, philote := range p.Hive.Philotes {
if p.ID == philote.ID {
continue
}
for _, channel := range philote.AccessKey.Read {
if message.Channel == channel {
philote.IncomingMessages <- message
break
}
}
}
}