summaryrefslogtreecommitdiff
path: root/chat/buddy.go
blob: d369c612704d4bf6b81c4542df0d0ab92ae02996 (plain)
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
package chat

import (
	"time"
)

// Buddy represents a user that participates in a chat.
// Read from the Receive channel to get incoming messages
type Buddy struct {
	Nick    string
	Receive chan Message
	room    *Room
}

func newBuddy(nick string, room *Room) *Buddy {
	return &Buddy{
		Nick:    nick,
		Receive: make(chan Message),
		room:    room,
	}
}

// Leave will remove the buddy from the room.
func (b *Buddy) Leave() {
	b.room.leave(b.Nick)
}

// Push pushes a message to the buddies Receive channel
func (b *Buddy) Push(msg Message) {
	go func() {
		t := time.NewTicker(time.Millisecond * 100)
		defer t.Stop()
		select {
		case b.Receive <- msg:
		case <-t.C:
		}
	}()
}

// Say sends a text as a chat message of this user to the connected room.
func (b *Buddy) Say(text string) {
	b.room.messages <- Message{
		Type: MsgChat,
		User: b.Nick,
		Text: text,
	}
}