/
live.go
executable file
·202 lines (187 loc) · 4.37 KB
/
live.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package controllers
import (
"container/list"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
_ "github.com/davecgh/go-spew/spew"
"github.com/gorilla/websocket"
"net/http"
"strings"
"time"
)
type LiveController struct {
MainController
}
/**
* Register Event Types
*/
type EventData interface{}
type Event struct {
event string
Name string
Email string
Fired int
Data []EventData
}
/**
* Register subscription and subscriber types
*/
type Subscriber struct {
Email string
Conn *websocket.Conn
}
type Subscription struct {
Archive []Event // All the events from the archive.
New <-chan Event // New events coming in.
}
const (
EVENT_JOIN = iota
EVENT_LEAVE
EVENT_MESSAGE
archiveSize = 20
)
/**
* Create necessary global WS channels
*/
var (
subscribe = make(chan Subscriber, 10)
unsubscribe = make(chan string, 10)
publish = make(chan Event, 10)
waitingList = list.New()
subscribers = list.New()
archive = list.New()
)
/**
* Basic Archive & Event functions
*/
func NewEvent(name string, email string, data []EventData) Event {
return Event{"push", name, email, int(time.Now().Unix()), data}
}
func NewArchive(event Event) {
if archive.Len() >= archiveSize {
archive.Remove(archive.Front())
}
archive.PushBack(event)
}
func GetEvents(lastReceived int) []Event { // GetEvents returns all events after lastReceived.
events := make([]Event, 0, archive.Len())
for event := archive.Front(); event != nil; event = event.Next() {
e := event.Value.(Event)
if e.Fired > int(lastReceived) {
events = append(events, e)
}
}
return events
}
/**
* Create join and leave funcs
*/
func Join(email string, ws *websocket.Conn) {
fmt.Printf("User joined: %v", email)
subscribe <- Subscriber{Email: email, Conn: ws}
}
func Leave(email string) {
fmt.Printf("User left: %v", email)
unsubscribe <- email
}
func isUserExist(subscribers *list.List, user string) bool {
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
if sub.Value.(Subscriber).Email == user {
return true
}
}
return false
}
/**
* Define a function to process all
* incoming and outgoing requests from
* our web sockets.
*/
func liveSockets() {
for {
select {
case sub := <-subscribe:
if !isUserExist(subscribers, sub.Email) {
subscribers.PushBack(sub)
// NewEvent := NewEvent("CLIENT.JOIN", sub.Email, []EventData{})
// spew.Dump(NewEvent)
// publish <- NewEvent
}
case event := <-publish:
for ch := waitingList.Back(); ch != nil; ch = ch.Prev() {
ch.Value.(chan bool) <- true
waitingList.Remove(ch)
}
BroadcastEvent(event)
NewArchive(event)
case unsub := <-unsubscribe:
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
if sub.Value.(Subscriber).Email == unsub {
// Close connection.
subscribers.Remove(sub)
ws := sub.Value.(Subscriber).Conn
if ws != nil {
ws.Close()
}
break
}
}
}
}
}
func BroadcastEvent(event Event) {
data, err := json.Marshal(event)
if err != nil {
return
}
for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
subEmail := strings.Trim(strings.ToLower(sub.Value.(Subscriber).Email), " ")
eventEmail := strings.Trim(strings.ToLower(event.Email), " ")
if subEmail == eventEmail {
ws := sub.Value.(Subscriber).Conn
if ws != nil {
if ws.WriteMessage(websocket.TextMessage, data) != nil {
unsubscribe <- sub.Value.(Subscriber).Email
}
}
}
}
}
/**
* Define init function to run our liveSockets in a goroutine
*/
func init() {
go liveSockets()
}
/**
* Define the funcs that respond to particular routes.
*/
func (this *LiveController) Join() {
// Verify user is logged in, get session data.
sess := this.GetSession("os-auth")
if sess == nil {
this.Redirect("/user/login/", 302)
return
}
m := sess.(map[string]interface{})
// Upgrade from http request to WebSocket.
ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
return
} else if err != nil {
beego.Error("Cannot setup WebSocket connection:", err)
return
}
// Join
Join(m["username"].(string), ws)
defer Leave(m["username"].(string))
// Receive requests from clients.
for {
_, _, err := ws.ReadMessage() // SECOND VARIABLE _ IS REPLY
if err != nil {
return
}
}
}