chat/message: Add PublicMsg.RenderSelf(...) to support old-style formatting
[ssh-chat] / chat / message / user.go
1 package message
2
3 import (
4         "errors"
5         "fmt"
6         "io"
7         "math/rand"
8         "regexp"
9         "sync"
10         "time"
11
12         "github.com/shazow/ssh-chat/set"
13 )
14
15 const messageBuffer = 5
16 const messageTimeout = 5 * time.Second
17 const reHighlight = `\b(%s)\b`
18 const timestampTimeout = 30 * time.Minute
19 const timestampLayout = "2006-01-02 15:04:05 UTC"
20
21 var ErrUserClosed = errors.New("user closed")
22
23 // User definition, implemented set Item interface and io.Writer
24 type User struct {
25         Identifier
26         Ignored  *set.Set
27         colorIdx int
28         joined   time.Time
29         msg      chan Message
30         done     chan struct{}
31
32         screen    io.WriteCloser
33         closeOnce sync.Once
34
35         mu      sync.Mutex
36         config  UserConfig
37         replyTo *User     // Set when user gets a /msg, for replying.
38         lastMsg time.Time // When the last message was rendered
39 }
40
41 func NewUser(identity Identifier) *User {
42         u := User{
43                 Identifier: identity,
44                 config:     DefaultUserConfig,
45                 joined:     time.Now(),
46                 msg:        make(chan Message, messageBuffer),
47                 done:       make(chan struct{}),
48                 Ignored:    set.New(),
49         }
50         u.setColorIdx(rand.Int())
51
52         return &u
53 }
54
55 func NewUserScreen(identity Identifier, screen io.WriteCloser) *User {
56         u := NewUser(identity)
57         u.screen = screen
58
59         return u
60 }
61
62 func (u *User) Joined() time.Time {
63         return u.joined
64 }
65
66 func (u *User) Config() UserConfig {
67         u.mu.Lock()
68         defer u.mu.Unlock()
69         return u.config
70 }
71
72 func (u *User) SetConfig(cfg UserConfig) {
73         u.mu.Lock()
74         u.config = cfg
75         u.mu.Unlock()
76 }
77
78 // Rename the user with a new Identifier.
79 func (u *User) SetID(id string) {
80         u.Identifier.SetID(id)
81         u.setColorIdx(rand.Int())
82 }
83
84 // ReplyTo returns the last user that messaged this user.
85 func (u *User) ReplyTo() *User {
86         u.mu.Lock()
87         defer u.mu.Unlock()
88         return u.replyTo
89 }
90
91 // SetReplyTo sets the last user to message this user.
92 func (u *User) SetReplyTo(user *User) {
93         u.mu.Lock()
94         defer u.mu.Unlock()
95         u.replyTo = user
96 }
97
98 // setColorIdx will set the colorIdx to a specific value, primarily used for
99 // testing.
100 func (u *User) setColorIdx(idx int) {
101         u.colorIdx = idx
102 }
103
104 // Disconnect user, stop accepting messages
105 func (u *User) Close() {
106         u.closeOnce.Do(func() {
107                 if u.screen != nil {
108                         u.screen.Close()
109                 }
110                 // close(u.msg) TODO: Close?
111                 close(u.done)
112         })
113 }
114
115 // Consume message buffer into the handler. Will block, should be called in a
116 // goroutine.
117 func (u *User) Consume() {
118         for {
119                 select {
120                 case <-u.done:
121                         return
122                 case m, ok := <-u.msg:
123                         if !ok {
124                                 return
125                         }
126                         u.HandleMsg(m)
127                 }
128         }
129 }
130
131 // Consume one message and stop, mostly for testing
132 func (u *User) ConsumeOne() Message {
133         return <-u.msg
134 }
135
136 // Check if there are pending messages, used for testing
137 func (u *User) HasMessages() bool {
138         select {
139         case msg := <-u.msg:
140                 u.msg <- msg
141                 return true
142         default:
143                 return false
144         }
145 }
146
147 // SetHighlight sets the highlighting regular expression to match string.
148 func (u *User) SetHighlight(s string) error {
149         re, err := regexp.Compile(fmt.Sprintf(reHighlight, s))
150         if err != nil {
151                 return err
152         }
153         u.mu.Lock()
154         u.config.Highlight = re
155         u.mu.Unlock()
156         return nil
157 }
158
159 func (u *User) render(m Message) string {
160         cfg := u.Config()
161         var out string
162         switch m := m.(type) {
163         case PublicMsg:
164                 if u == m.From() {
165                         out += m.RenderSelf(cfg)
166                 } else {
167                         out += m.RenderFor(cfg)
168                 }
169         case *PrivateMsg:
170                 out += m.Render(cfg.Theme)
171                 if cfg.Bell {
172                         out += Bel
173                 }
174         default:
175                 out += m.Render(cfg.Theme)
176         }
177         if cfg.Timestamp {
178                 return cfg.Theme.Timestamp(m.Timestamp()) + "  " + out + Newline
179         }
180         return out + Newline
181 }
182
183 // writeMsg renders the message and attempts to write it, will Close the user
184 // if it fails.
185 func (u *User) writeMsg(m Message) error {
186         r := u.render(m)
187         _, err := u.screen.Write([]byte(r))
188         if err != nil {
189                 logger.Printf("Write failed to %s, closing: %s", u.Name(), err)
190                 u.Close()
191         }
192         return err
193 }
194
195 // HandleMsg will render the message to the screen, blocking.
196 func (u *User) HandleMsg(m Message) error {
197         u.mu.Lock()
198         cfg := u.config
199         lastMsg := u.lastMsg
200         u.lastMsg = m.Timestamp()
201         injectTimestamp := !lastMsg.IsZero() && cfg.Timestamp && u.lastMsg.Sub(lastMsg) > timestampTimeout
202         u.mu.Unlock()
203
204         if injectTimestamp {
205                 // Inject a timestamp at most once every timestampTimeout between message intervals
206                 ts := NewSystemMsg(fmt.Sprintf("Timestamp: %s", m.Timestamp().UTC().Format(timestampLayout)), u)
207                 if err := u.writeMsg(ts); err != nil {
208                         return err
209                 }
210         }
211
212         return u.writeMsg(m)
213 }
214
215 // Add message to consume by user
216 func (u *User) Send(m Message) error {
217         select {
218         case <-u.done:
219                 return ErrUserClosed
220         case u.msg <- m:
221         case <-time.After(messageTimeout):
222                 logger.Printf("Message buffer full, closing: %s", u.Name())
223                 u.Close()
224                 return ErrUserClosed
225         }
226         return nil
227 }
228
229 // Container for per-user configurations.
230 type UserConfig struct {
231         Highlight *regexp.Regexp
232         Bell      bool
233         Quiet     bool
234         Timestamp bool
235         Theme     *Theme
236 }
237
238 // Default user configuration to use
239 var DefaultUserConfig UserConfig
240
241 func init() {
242         DefaultUserConfig = UserConfig{
243                 Bell:      true,
244                 Quiet:     false,
245                 Timestamp: false,
246         }
247
248         // TODO: Seed random?
249 }