-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.go
309 lines (277 loc) · 7.82 KB
/
websockets.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main
import (
"code.google.com/p/go.net/websocket"
// "fmt"
"io"
"launchpad.net/mgo"
"launchpad.net/mgo/bson"
"log"
"net/http"
"sync"
)
var (
db *mgo.Database
manager *ConnectionManager
)
type SocketCmd struct {
Cmd string `json:"cmd"`
Client string `json:"client"`
Params map[string]interface{} `json:"params"`
}
type OutgoingCmd struct {
Cmd string `json:"cmd"`
Params interface{} `json:"params"`
}
type CreateEventParams struct {
UserConn *websocket.Conn
EventId string `json:"event_id"`
UserId string `json:"user_id" bson:"user_id"`
}
type Event struct {
Id string `json:"event_id" bson:"event_id"`
UserId string `json:"user_id" bson:"user_id"`
Upcoming map[string][]string `json:"upcoming" bson:"upcoming,omitempty"`
Playing string `json:"playing" bson:"playing,omitempty"`
History []*PastTrack `json:"history" bson:"history,omitempty"`
}
type Track struct {
Votes int
Id string
}
type UpcomingTrack struct {
TrackId string `bson:"track_id"`
Upvoters []string `bson:"upvoters"`
}
type PastTrack struct {
TrackId string `bson:"track_id"`
}
type UpvoteParams struct {
UserId string
EventId string
TrackId string
Remove bool
}
type AddTrackParams struct {
EventId string `json:"event_id"`
TrackId string `json:"track_id"`
UserId string `json:"user_id"`
}
type StartTrackParams AddTrackParams
type SetAuthParams struct {
UserId string `json:"user_id"`
}
/*
func (s *SocketCmd) String() string {
return fmt.Sprintf("[cmd: %s, params: %v]", s.Cmd, s.Params)
}
*/
type ConnectionManager struct {
Connected []*websocket.Conn
ConnectionLock *sync.Mutex
CreateEvent chan *CreateEventParams
Upvotes chan *UpvoteParams
StartTrack chan *StartTrackParams
AddTrack chan *AddTrackParams
SetAuth chan *SetAuthParams
Login chan *websocket.Conn
Logout chan *websocket.Conn
}
func NewConnectionManager() *ConnectionManager {
m := &ConnectionManager{
Connected: []*websocket.Conn{},
ConnectionLock: new(sync.Mutex),
CreateEvent: make(chan *CreateEventParams),
Upvotes: make(chan *UpvoteParams),
AddTrack: make(chan *AddTrackParams),
StartTrack: make(chan *StartTrackParams),
SetAuth: make(chan *SetAuthParams),
Login: make(chan *websocket.Conn),
Logout: make(chan *websocket.Conn),
}
go m.listenForNewEvents()
go m.listenForUpvotes()
go m.listenForLogins()
go m.listenForLogouts()
go m.listenForAdds()
go m.listenForTrackStarts()
return m
}
func (m *ConnectionManager) listenForNewEvents() {
for eventInfo := range m.CreateEvent {
event, err := GetEvent(eventInfo.EventId, eventInfo.UserId)
if err != nil {
log.Println("FUCK BALLS")
continue
}
websocket.JSON.Send(eventInfo.UserConn, &OutgoingCmd{Cmd: "event_info", Params: event})
}
}
func (m *ConnectionManager) listenForTrackStarts() {
events := db.C("events")
for trackStart := range m.StartTrack {
_, err := GetEvent(trackStart.EventId, trackStart.UserId)
if err != nil {
log.Println("Unable to retrieve event when starting track play: ", err.Error())
continue
}
err = events.Update(bson.M{"event_id": trackStart.EventId}, bson.M{"$set": bson.M{"now_playing": trackStart.TrackId}})
if err != nil {
log.Println("Unable to update event when starting rack play: ", err.Error())
continue
}
manager.Broadcast(&OutgoingCmd{Cmd: "start_track", Params: map[string]interface{}{"track_id": trackStart.TrackId, "event_id": trackStart.EventId}})
}
}
func (m *ConnectionManager) listenForLogins() {
for conn := range m.Login {
m.Connected = append(m.Connected, conn)
}
}
// get or create an event by id. If you create it, you are the host.
func GetEvent(eventId string, userId string) (*Event, error) {
c := db.C("events")
event := new(Event)
err := c.Find(bson.M{"event_id": eventId}).One(&event)
if err != nil {
if err == mgo.NotFound {
event.Id = eventId
event.UserId = userId
err = c.Insert(event)
if err != nil {
log.Println("ERROR inserting: ", err.Error())
return nil, err
}
} else {
log.Println("ERROR querying: ", err.Error())
return nil, err
}
}
return event, nil
}
func (m *ConnectionManager) listenForAdds() {
c := db.C("events")
for add := range m.AddTrack {
selector := bson.M{"event_id": add.EventId}
var event Event
err := c.Find(selector).One(&event)
if err != nil {
log.Println("ERROR querying for track: ", err.Error())
continue
}
if _, ok := event.Upcoming[add.TrackId]; ok {
continue
}
err = c.Update(selector, bson.M{"$addToSet": bson.M{"upcoming." + add.TrackId: add.UserId}})
if err != nil {
log.Println("ERROR adding track: ", err.Error())
log.Println(selector)
continue
}
err = c.Find(selector).One(&event)
if err != nil {
log.Println("ERROR querying for track: ", err.Error())
continue
}
m.Broadcast(&OutgoingCmd{Cmd: "add_track", Params: bson.M{"track_id": add.TrackId, "upvoters": event.Upcoming[add.TrackId]}})
}
}
func (m *ConnectionManager) listenForUpvotes() {
c := db.C("events")
for like := range m.Upvotes {
selector := bson.M{"event_id": like.EventId}
var action string
if like.Remove {
action = "$pull"
} else {
action = "$addToSet"
}
err := c.Update(selector, bson.M{action: bson.M{"upcoming." + like.TrackId: like.UserId}})
if err != nil {
log.Println("ERROR adding upvote: ", err.Error())
log.Println(selector)
}
var event Event
err = c.Find(selector).One(&event)
if err != nil {
log.Println("ERROR getting event info: ", err.Error())
continue
}
m.Broadcast(&OutgoingCmd{Cmd: "upvote", Params: bson.M{"track_id": like.TrackId, "upvoters": event.Upcoming[like.TrackId]}})
}
}
func (m *ConnectionManager) listenForLogouts() {
for conn := range m.Logout {
for i, other := range m.Connected {
if conn == other {
m.Connected = append(m.Connected[:i], m.Connected[i:len(m.Connected)-1]...)
log.Println("Found matching connection, breaking.")
return
}
}
}
}
func (m *ConnectionManager) Broadcast(v interface{}) {
m.ConnectionLock.Lock()
for _, conn := range m.Connected {
websocket.JSON.Send(conn, v)
}
m.ConnectionLock.Unlock()
}
func SocketHandler(sock *websocket.Conn) {
log.Println("Added new websocket connection ++++++++++++++++++++++++++++++++++++++++")
manager.Login <- sock
var cmd SocketCmd
for {
err := websocket.JSON.Receive(sock, &cmd)
if err != nil {
if err == io.EOF {
log.Println("User disconnected ----------------------------------------")
} else {
log.Println("ERROR:", err.Error())
}
break
}
log.Println(cmd)
switch cmd.Cmd {
case "add_track":
manager.AddTrack <- &AddTrackParams{
TrackId: cmd.Params["track_id"].(string),
UserId: cmd.Params["user_id"].(string),
EventId: cmd.Params["event_id"].(string),
}
case "upvote_track":
manager.Upvotes <- &UpvoteParams{
UserId: cmd.Params["user_id"].(string),
EventId: cmd.Params["event_id"].(string),
TrackId: cmd.Params["track_id"].(string),
Remove: cmd.Params["remove"].(bool),
}
case "start_track":
manager.StartTrack <- &StartTrackParams{
TrackId: cmd.Params["track_id"].(string),
UserId: cmd.Params["user_id"].(string),
EventId: cmd.Params["event_id"].(string),
}
case "login":
manager.CreateEvent <- &CreateEventParams{
UserConn: sock,
UserId: cmd.Params["user_id"].(string),
EventId: cmd.Params["event_id"].(string),
}
default:
log.Println("Didn't understand this command: ", cmd)
}
}
manager.Logout <- sock
}
func main() {
s, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
db = s.DB("coca")
manager = NewConnectionManager()
log.Println("serving on :8080")
http.Handle("/socket", websocket.Handler(SocketHandler))
http.ListenAndServe(":8080", nil)
}