This repository has been archived by the owner on Jan 30, 2020. It is now read-only.
/
chatengine.go
402 lines (355 loc) · 11.1 KB
/
chatengine.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package siteengines
import (
"strconv"
"time"
"github.com/hoisie/web"
. "github.com/xyproto/genericsite"
. "github.com/xyproto/onthefly"
"github.com/xyproto/pinterface"
. "github.com/xyproto/webhandle"
)
// An Engine is a specific piece of a website
// This part handles the "chat" pages
type ChatEngine struct {
chatState *ChatState
state pinterface.IUserState
}
type ChatState struct {
active pinterface.ISet // A list of all users that are in the chat, must correspond to the users in permissions.UserState.users
said pinterface.IList // A list of everything that has been said so far
userInfo pinterface.IHashMap // Info about a chat user - last seen, preferred number of lines etc
host pinterface.IHost // A host
}
func NewChatEngine(userState pinterface.IUserState) (*ChatEngine, error) {
chatState := new(ChatState)
creator := userState.Creator()
if activeSet, err := creator.NewSet("active"); err != nil {
return nil, err
} else {
chatState.active = activeSet
}
if saidList, err := creator.NewList("said"); err != nil {
return nil, err
} else {
chatState.said = saidList
}
if userInfoHashMap, err := creator.NewHashMap("userInfo"); err != nil {
return nil, err
} else {
chatState.userInfo = userInfoHashMap
}
return &ChatEngine{chatState, userState}, nil
}
func (ce *ChatEngine) ServePages(basecp BaseCP, menuEntries MenuEntries) {
chatCP := basecp(ce.state)
chatCP.ContentTitle = "Chat"
chatCP.ExtraCSSurls = append(chatCP.ExtraCSSurls, "/css/chat.css")
tvgf := DynamicMenuFactoryGenerator(menuEntries)
tvg := tvgf(ce.state)
web.Get("/chat", chatCP.WrapSimpleContextHandle(ce.GenerateChatCurrentUser(), tvg))
web.Post("/say", ce.GenerateSayCurrentUser())
web.Get("/css/chat.css", ce.GenerateCSS(chatCP.ColorScheme))
web.Post("/setchatlines", ce.GenerateSetChatLinesCurrentUser())
// For debugging
web.Get("/getchatlines", ce.GenerateGetChatLinesCurrentUser())
}
func (ce *ChatEngine) SetLines(username string, lines int) {
ce.chatState.userInfo.Set(username, "lines", strconv.Itoa(lines))
}
func (ce *ChatEngine) GetLines(username string) int {
val, err := ce.chatState.userInfo.Get(username, "lines")
if err != nil {
// The default
return 20
}
num, err := strconv.Atoi(val)
if err != nil {
// The default
return 20
}
return num
}
// Mark a user as seen
func (ce *ChatEngine) Seen(username string) {
now := time.Now()
encodedTime, err := now.GobEncode()
if err != nil {
panic("ERROR: Can't encode the time")
}
ce.chatState.userInfo.Set(username, "lastseen", string(encodedTime))
}
// Checks if the user has been seen lately (within 12 hours ago)
func (ce *ChatEngine) SeenLately(username string) bool {
encodedTime, err := ce.chatState.userInfo.Get(username, "lastseen")
if err != nil {
return false
}
var then time.Time
err = then.GobDecode([]byte(encodedTime))
if err != nil {
return false
}
notTooLongDuration, err := time.ParseDuration("-12h")
if err != nil {
return false
}
notTooLongAgo := time.Now().Add(notTooLongDuration)
if then.After(notTooLongAgo) {
return true
}
return false
}
func (ce *ChatEngine) GetLastSeen(username string) string {
encodedTime, err := ce.chatState.userInfo.Get(username, "lastseen")
if err == nil {
var then time.Time
err = then.GobDecode([]byte(encodedTime))
if err == nil {
timestamp := then.String()
return timestamp[11:19]
}
}
return "never"
}
func (ce *ChatEngine) IsChatting(username string) bool {
encodedTime, err := ce.chatState.userInfo.Get(username, "lastseen")
if err == nil {
var then time.Time
err = then.GobDecode([]byte(encodedTime))
if err == nil {
elapsed := time.Since(then)
if elapsed.Minutes() > 20 {
// 20 minutes since last seen saying anything, set as not chatting
ce.SetChatting(username, false)
return false
}
}
}
// TODO: Just return true instead of retrieving the data
return ce.state.BooleanField(username, "chatting")
}
// Set "chatting" to "true" or "false" for a given user
func (ce *ChatEngine) SetChatting(username string, val bool) {
ce.state.SetBooleanField(username, "chatting", val)
}
func (ce *ChatEngine) JoinChat(username string) {
// Join the chat
ce.chatState.active.Add(username)
// Change the chat status for the user
ce.SetChatting(username, true)
// Mark the user as seen
ce.Seen(username)
}
func (ce *ChatEngine) Say(username, text string) {
timestamp := time.Now().String()
textline := timestamp[11:19] + " " + username + "> " + text
ce.chatState.said.Add(textline)
// Store the timestamp for when the user was last seen as well
ce.Seen(username)
}
func LeaveChat(ce *ChatEngine, username string) {
// Leave the chat
ce.chatState.active.Del(username)
// Change the chat status for the user
ce.SetChatting(username, false)
}
// Get current users of the chat
func (ce *ChatEngine) ChatUsers() []string {
chatUsernames, err := ce.chatState.active.GetAll()
if err != nil {
return []string{}
}
return chatUsernames
}
// Get current text of the chat
func (ce *ChatEngine) ChatText() []string {
chatText, err := ce.chatState.said.GetAll()
if err != nil {
return []string{}
}
return chatText
}
// Get the last N entries
func (ce *ChatEngine) GetLastChatText(n int) []string {
chatText, err := ce.chatState.said.GetLastN(n)
if err != nil {
return []string{}
}
return chatText
}
func (ce *ChatEngine) chatText(lines int) string {
if lines == -1 {
return ""
}
retval := "<div id='chatText'>"
// Show N lines of chat text
for _, said := range ce.GetLastChatText(lines) {
retval += said + "<br />"
}
return retval + "</div>"
}
func (ce *ChatEngine) GenerateChatCurrentUser() SimpleContextHandle {
return func(ctx *web.Context) string {
username := ce.state.Username(ctx.Request)
if username == "" {
return "No user logged in"
}
if !ce.state.IsLoggedIn(username) {
return "Not logged in"
}
ce.JoinChat(username)
// TODO: Add a button for someone to see the entire chat
// TODO: Add some protection against random monkeys that only fling poo
retval := "<h2>Hi " + username + "</h2>"
seenusers := ""
for _, otherUser := range ce.ChatUsers() {
if otherUser == username {
continue
}
if ce.SeenLately(otherUser) {
seenusers += " " + otherUser + ", last seen " + ce.GetLastSeen(otherUser) + "<br />"
}
}
// Add a list of participants that has been seen lately, if there are any
if seenusers != "" {
retval += "<br />Other participants:<br />"
retval += seenusers
retval += "<br />"
}
retval += "<div style='background-color: white; padding: 1em;'>"
retval += ce.chatText(ce.GetLines(username))
retval += "</div>"
retval += "<br />"
retval += JS("var fastestPolling = 400;")
retval += JS("var slowestPolling = 64000;")
retval += JS("var pollInterval = fastestPolling;")
retval += JS("var pollID = 0;")
// The say() function for submitting text over ajax (a post request), clearing the text intput field and updating the chat text.
// Also sets the polling interval to the fastest value.
retval += JS(`function say(text) {
inactivityCounter = 0;
pollInterval = fastestPolling;
$.post('/say', {said:$('#sayText').val()}, function(data) { $('#sayText').val(''); $('#chatText').html(data); });
}`)
// Call say() at return
retval += "<input size='60' id='sayText' name='said' type='text' onKeypress=\"if (event.keyCode == 13) { say($('#sayText').val()); };\">"
// Cal say() at the click of the button
retval += "<button onClick='say();'>Say</button>"
// Focus on the text input
retval += JS(Focus("#sayText"))
// Update the chat text. Reduce the poll interval at every poll.
// When the user does something, the polling interval will be reset to something quicker.
retval += JS(`function UpdateChat() {
if (pollInterval < slowestPolling) {
pollInterval *= 2;
clearInterval(pollID);
pollID = setInterval(UpdateChat, pollInterval);
}
$.post('/say', {}, function(data) { $('#chatText').html(data); });
}`)
retval += JS("pollID = setInterval(UpdateChat, pollInterval);")
// A function for setting the preferred number of lines
retval += JS("function setlines(numlines) { $.post('/setchatlines', {lines:numlines}, function(data) { $('#chatText').html(data); " + ScrollDownAnimated() + "}); }")
// A button for viewing 20 lines at a time
retval += "<button onClick='setlines(20);'>20</button>"
// A button for viewing 50 lines at a time
retval += "<button onClick='setlines(50);'>50</button>"
// A button for viewing 99999 lines at a time
retval += "<button onClick='setlines(99999);'>99999</button>"
// For viewing all the text so far
return retval
}
}
func (ce *ChatEngine) GenerateSayCurrentUser() SimpleContextHandle {
return func(ctx *web.Context) string {
username := ce.state.Username(ctx.Request)
if username == "" {
return "No user logged in"
}
if !ce.state.IsLoggedIn(username) {
return "Not logged in"
}
if !ce.IsChatting(username) {
return "Not currently chatting"
}
said, found := ctx.Params["said"]
if !found || said == "" {
// Return the text instead of giving an error for easy use of /say to refresh the content
// Note that as long as Say below isn't called, the user will be marked as inactive eventually
return ce.chatText(ce.GetLines(username))
}
ce.Say(username, CleanUserInput(said))
return ce.chatText(ce.GetLines(username))
}
}
func (ce *ChatEngine) GenerateGetChatLinesCurrentUser() SimpleContextHandle {
return func(ctx *web.Context) string {
username := ce.state.Username(ctx.Request)
if username == "" {
return "No user logged in"
}
if !ce.state.IsLoggedIn(username) {
return "Not logged in"
}
if !ce.IsChatting(username) {
return "Not currently chatting"
}
num := ce.GetLines(username)
return strconv.Itoa(num)
}
}
func (ce *ChatEngine) GenerateSetChatLinesCurrentUser() SimpleContextHandle {
return func(ctx *web.Context) string {
username := ce.state.Username(ctx.Request)
if username == "" {
return "No user logged in"
}
if !ce.state.IsLoggedIn(username) {
return "Not logged in"
}
if !ce.IsChatting(username) {
return "Not currently chatting"
}
lines, found := ctx.Params["lines"]
if !found || lines == "" {
return MessageOKback("Set chat lines", "Missing value for preferred number of lines")
}
num, err := strconv.Atoi(lines)
if err != nil {
return MessageOKback("Set chat lines", "Invalid number of lines: "+lines)
}
// Set the preferred number of lines for this user
ce.SetLines(username, num)
return ce.chatText(num)
}
}
func (ce *ChatEngine) GenerateCSS(cs *ColorScheme) SimpleContextHandle {
return func(ctx *web.Context) string {
ctx.ContentType("css")
return `
.yes {
background-color: #90ff90;
color: black;
}
.no {
background-color: #ff9090;
color: black;
}
.username:link { color: green; }
.username:visited { color: green; }
.username:hover { color: green; }
.username:active { color: green; }
.whitebg {
background-color: white;
}
.darkgrey:link { color: #404040; }
.darkgrey:visited { color: #404040; }
.darkgrey:hover { color: #404040; }
.darkgrey:active { color: #404040; }
#chatText {
background-color: white;
}
`
//
}
}