13 const messageBuffer = 20
14 const reHighlight = `\b(%s)\b`
16 var ErrUserClosed = errors.New("user closed")
18 // User definition, implemented set Item interface and io.Writer
28 replyTo *User // Set when user gets a /msg, for replying.
33 func NewUser(identity Identifier) *User {
36 Config: *DefaultUserConfig,
38 msg: make(chan Message, messageBuffer),
39 done: make(chan struct{}, 1),
41 u.SetColorIdx(rand.Int())
46 func NewUserScreen(identity Identifier, screen io.WriteCloser) *User {
47 u := NewUser(identity)
54 // Rename the user with a new Identifier.
55 func (u *User) SetId(id string) {
56 u.Identifier.SetId(id)
57 u.SetColorIdx(rand.Int())
60 // ReplyTo returns the last user that messaged this user.
61 func (u *User) ReplyTo() *User {
65 // SetReplyTo sets the last user to message this user.
66 func (u *User) SetReplyTo(user *User) {
70 // ToggleQuietMode will toggle whether or not quiet mode is enabled
71 func (u *User) ToggleQuietMode() {
72 u.Config.Quiet = !u.Config.Quiet
75 // SetColorIdx will set the colorIdx to a specific value, primarily used for
77 func (u *User) SetColorIdx(idx int) {
81 // Block until user is closed
82 func (u *User) Wait() {
86 // Disconnect user, stop accepting messages
87 func (u *User) Close() {
104 // Consume message buffer into an io.Writer. Will block, should be called in a
106 // TODO: Not sure if this is a great API.
107 func (u *User) Consume(out io.Writer) {
108 for m := range u.msg {
113 // Consume one message and stop, mostly for testing
114 func (u *User) ConsumeChan() <-chan Message {
118 // SetHighlight sets the highlighting regular expression to match string.
119 func (u *User) SetHighlight(s string) error {
120 re, err := regexp.Compile(fmt.Sprintf(reHighlight, s))
124 u.Config.Highlight = re
128 func (u *User) render(m Message) string {
129 switch m := m.(type) {
131 return m.RenderFor(u.Config) + Newline
133 u.SetReplyTo(m.From())
134 return m.Render(u.Config.Theme) + Newline
136 return m.Render(u.Config.Theme) + Newline
140 func (u *User) HandleMsg(m Message, out io.Writer) {
142 _, err := out.Write([]byte(r))
144 logger.Printf("Write failed to %s, closing: %s", u.Name(), err)
149 // Add message to consume by user
150 func (u *User) Send(m Message) error {
161 logger.Printf("Msg buffer full, closing: %s", u.Name())
168 // Container for per-user configurations.
169 type UserConfig struct {
170 Highlight *regexp.Regexp
176 // Default user configuration to use
177 var DefaultUserConfig *UserConfig
180 DefaultUserConfig = &UserConfig{
185 // TODO: Seed random?