func (c Refresh) Room(user string) revel.Result { subscription := chatroom.Subscribe() defer subscription.Cancel() events := subscription.Archive for i, _ := range events { if events[i].User == user { events[i].User = "******" } } return c.Render(user, events) }
func (c WebSocket) RoomSocket(user string, ws *websocket.Conn) revel.Result { // Join the room. subscription := chatroom.Subscribe() defer subscription.Cancel() chatroom.Join(user) defer chatroom.Leave(user) // Send down the archive. for _, event := range subscription.Archive { if websocket.JSON.Send(ws, &event) != nil { // They disconnected return nil } } // In order to select between websocket messages and subscription events, we // need to stuff websocket events into a channel. newMessages := make(chan string) go func() { var msg string for { err := websocket.Message.Receive(ws, &msg) if err != nil { close(newMessages) return } newMessages <- msg } }() // Now listen for new events from either the websocket or the chatroom. for { select { case event := <-subscription.New: if websocket.JSON.Send(ws, &event) != nil { // They disconnected. return nil } case msg, ok := <-newMessages: // If the channel is closed, they disconnected. if !ok { return nil } // Otherwise, say something. chatroom.Say(user, msg) } } return nil }
func (c LongPolling) WaitMessages(lastReceived int) revel.Result { subscription := chatroom.Subscribe() defer subscription.Cancel() // See if anything is new in the archive. var events []chatroom.Event for _, event := range subscription.Archive { if event.Timestamp > lastReceived { events = append(events, event) } } // If we found one, grand. if len(events) > 0 { return c.RenderJson(events) } // Else, wait for something new. event := <-subscription.New return c.RenderJson([]chatroom.Event{event}) }