/
history.go
161 lines (145 loc) · 4.87 KB
/
history.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
package app
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strconv"
"time"
"github.com/labstack/echo"
"github.com/topfreegames/mqttbot/es"
"github.com/topfreegames/mqttbot/logger"
"gopkg.in/olivere/elastic.v5"
)
// Message represents a chat message
type Message struct {
Timestamp time.Time `json:"timestamp"`
Payload string `json:"payload"`
Topic string `json:"topic"`
}
// HistoryHandler is the handler responsible for sending the rooms history to the player
func HistoryHandler(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
esclient := es.GetESClient()
c.Set("route", "History")
topic := c.ParamValues()[0]
userID := c.QueryParam("userid")
from, err := strconv.Atoi(c.QueryParam("from"))
limit, err := strconv.Atoi(c.QueryParam("limit"))
if limit == 0 {
limit = 10
}
logger.Logger.Debugf("user %s is asking for history for topic %s with args from=%d and limit=%d", userID, topic, from, limit)
rc := app.RedisClient.Pool.Get()
defer rc.Close()
rc.Send("MULTI")
rc.Send("GET", userID)
rc.Send("GET", fmt.Sprintf("%s-%s", userID, topic))
r, err := rc.Do("EXEC")
if err != nil {
return err
}
redisResults := (r.([]interface{}))
if redisResults[0] != nil && redisResults[1] != nil {
boolQuery := elastic.NewBoolQuery()
// FIXME: Dont think this is the best way for searching
matchTopicQuery := elastic.NewMatchQuery("topic", topic).MinimumShouldMatch("100%")
boolQuery.Filter(matchTopicQuery)
searchResults, err := esclient.Search().Index("chat").Query(boolQuery).
Sort("timestamp", false).From(from).Size(limit).Do(context.TODO())
if err != nil {
return err
}
messages := []Message{}
var ttyp Message
for _, item := range searchResults.Each(reflect.TypeOf(ttyp)) {
if t, ok := item.(Message); ok {
messages = append(messages, t)
}
}
return c.JSON(http.StatusOK, messages)
}
return c.String(echo.ErrUnauthorized.Code, echo.ErrUnauthorized.Message)
}
}
// HistorySinceHandler is the handler responsible for sending the rooms history to the player based in a initial date
func HistorySinceHandler(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
esclient := es.GetESClient()
c.Set("route", "HistorySince")
topic := c.ParamValues()[0]
userID := c.QueryParam("userid")
from, err := strconv.Atoi(c.QueryParam("from"))
limit, err := strconv.Atoi(c.QueryParam("limit"))
since, err := strconv.ParseInt(c.QueryParam("since"), 10, 64)
defaultLimit := 10
if limitFromEnv := os.Getenv("HISTORYSINCE_LIMIT"); limitFromEnv != "" {
defaultLimit, err = strconv.Atoi(limitFromEnv)
}
if limit == 0 {
limit = defaultLimit
}
logger.Logger.Debugf("user %s is asking for history for topic %s with args from=%d, limit=%d and since=%d", userID, topic, from, limit, since)
rc := app.RedisClient.Pool.Get()
defer rc.Close()
rc.Send("MULTI")
rc.Send("GET", userID)
rc.Send("GET", fmt.Sprintf("%s-%s", userID, topic))
var r interface{}
err = WithSegment("redis", c, func() error {
r, err = rc.Do("EXEC")
return err
})
if err != nil {
return err
}
logger.Logger.Debugf("Authenticating user with userID=%s and topic=%s", userID, topic)
redisResults := (r.([]interface{}))
if redisResults[0] != nil && redisResults[1] != nil {
boolQuery := elastic.NewBoolQuery()
matchQuery := elastic.NewMatchPhraseQuery("topic", topic)
rangeQuery := elastic.NewRangeQuery("timestamp").
From(since * 1000). // FIXME: The client should send time in milliseconds
To(nil).
IncludeLower(true).
IncludeUpper(true)
boolQuery.Must(matchQuery, rangeQuery)
var searchResults *elastic.SearchResult
err = WithSegment("elasticsearch", c, func() error {
searchResults, err = esclient.Search().Index("chat").Query(boolQuery).
Sort("timestamp", false).From(from).Size(limit).Do(context.TODO())
return err
})
if err != nil {
return err
}
messages := []Message{}
var ttyp Message
for _, item := range searchResults.Each(reflect.TypeOf(ttyp)) {
if t, ok := item.(Message); ok {
messages = append(messages, t)
}
}
var resStr []byte
err = WithSegment("elasticsearch", c, func() error {
resStr, err = json.Marshal(messages)
return err
})
if err != nil {
return err
}
logger.Logger.Debugf(
"responded to user %s history for topic %s with args from=%d limit=%d and since=%d with code=%d and message=%s",
userID, topic, from, limit, since, http.StatusOK, string(resStr),
)
return c.JSON(http.StatusOK, messages)
}
logger.Logger.Debugf(
"responded to user %s history for topic %s with args from=%d limit=%d and since=%d with code=%d and message=%s",
userID, topic, from, limit, since, echo.ErrUnauthorized.Code, echo.ErrUnauthorized.Message,
)
return c.String(echo.ErrUnauthorized.Code, echo.ErrUnauthorized.Message)
}
}