This repository has been archived by the owner on Dec 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
frontend.go
229 lines (203 loc) · 6.45 KB
/
frontend.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
package gossip
import (
"database/sql"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/parkr/gossip/database"
"github.com/parkr/gossip/template"
)
func ensureLeadingHash(room string) string {
if strings.HasPrefix(room, "#") {
return room
}
return "#" + room
}
func (h *Handler) Index(w http.ResponseWriter, r *http.Request) {
oldURL := r.URL
r.URL = &url.URL{
Scheme: oldURL.Scheme,
Opaque: oldURL.Opaque,
User: oldURL.User,
Host: oldURL.Host,
Path: "/room/%23" + h.DefaultRoom(),
RawPath: "/room/%23" + h.DefaultRoom(),
ForceQuery: oldURL.ForceQuery,
RawQuery: oldURL.RawQuery,
Fragment: oldURL.Fragment,
}
h.LatestMessagesByRoom(w, r)
}
func (h *Handler) Search(w http.ResponseWriter, r *http.Request) {
query := r.FormValue("q")
if query == "" {
http.Error(w, "no search term given", http.StatusBadRequest)
return
}
if len(query) < 3 {
http.Error(w, "search term must be 3+ characters long", http.StatusBadRequest)
return
}
cacheKey := "search-" + query
messages, err := h.FetchAndCacheList(r, cacheKey, func() ([]database.Message, error) {
return h.DB.ListByFuzzyMessage(query)
})
if err == sql.ErrNoRows || len(messages) == 0 {
http.Error(w, "no results for "+query, http.StatusNotFound)
return
}
if err != nil {
fmt.Fprintf(w, "\n\ncouldn't fetch messages: %+v", err)
http.Error(w, "couldn't fetch messages", http.StatusInternalServerError)
return
}
messagesGroupedByRoom := map[string][]database.Message{}
for _, message := range messages {
if _, ok := messagesGroupedByRoom[message.Room]; !ok {
messagesGroupedByRoom[message.Room] = []database.Message{}
}
messagesGroupedByRoom[message.Room] = append(messagesGroupedByRoom[message.Room], message)
}
data := &template.SearchTemplateData{
Results: messagesGroupedByRoom,
Total: len(messages),
Rooms: h.AllRooms(),
Query: query,
}
if err := template.SearchTemplate.Execute(w, data); err != nil {
fmt.Fprintf(w, "\n\n%+v", err)
}
}
func (h *Handler) LatestMessagesByRoom(w http.ResponseWriter, r *http.Request) {
unescapedURLPath, err := url.PathUnescape(r.URL.Path)
if err != nil {
LogWithRequestID(r, fmt.Sprintf("Couldn't unescape URL.Path '%s': %+v", r.URL.Path, err))
unescapedURLPath = r.URL.Path
}
room := ensureLeadingHash(strings.TrimPrefix(unescapedURLPath, "/room/"))
limit := resultsLimit(r)
cacheKey := "messages-by-room-" + room + "-" + fmt.Sprintf("%d", limit)
messages, err := h.FetchAndCacheList(r, cacheKey, func() ([]database.Message, error) {
return h.DB.LatestMessagesByRoom(room, limit)
})
if err == sql.ErrNoRows || len(messages) == 0 {
http.Error(w, "no results for "+room, http.StatusNotFound)
return
}
if err != nil {
fmt.Fprintf(w, "\n\ncouldn't fetch messages: %+v", err)
http.Error(w, "couldn't fetch messages", http.StatusInternalServerError)
return
}
data := &template.ListTemplateData{
Messages: messages,
Rooms: h.AllRooms(),
CurrentRoom: room,
}
if err := template.ListTemplate.Execute(w, data); err != nil {
fmt.Fprintf(w, "\n\n%+v", err)
}
}
func (h *Handler) LatestMessagesByAuthor(w http.ResponseWriter, r *http.Request) {
author := strings.TrimPrefix(r.URL.Path, "/messages/by/")
limit := resultsLimit(r)
cacheKey := "messages-by-author-" + author + "-" + fmt.Sprintf("%d", limit)
messages, err := h.FetchAndCacheList(r, cacheKey, func() ([]database.Message, error) {
return h.DB.LatestMessagesByAuthor(author, limit)
})
if err == sql.ErrNoRows || len(messages) == 0 {
http.Error(w, "no results for "+author, http.StatusNotFound)
return
}
if err != nil {
fmt.Fprintf(w, "\n\ncouldn't fetch messages: %+v", err)
http.Error(w, "couldn't fetch messages", http.StatusInternalServerError)
return
}
data := &template.ListTemplateData{
Messages: messages,
Rooms: h.AllRooms(),
CurrentAuthor: author,
}
if err := template.ListTemplate.Execute(w, data); err != nil {
fmt.Fprintf(w, "\n\n%+v", err)
}
}
func (h *Handler) MessageContext(w http.ResponseWriter, r *http.Request) {
limit := 5
messageIDStr := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/messages/"), "/context")
if messageIDStr == "" {
http.Error(w, "no message id given", http.StatusBadRequest)
return
}
messageID, err := strconv.Atoi(messageIDStr)
if err != nil || messageID == 0 {
http.Error(w, "invalid message id", http.StatusBadRequest)
return
}
cacheKey := "message-" + messageIDStr
message, err := h.FetchAndCacheGet(r, cacheKey, func() (*database.Message, error) {
return h.DB.Find(messageID)
})
if err == sql.ErrNoRows {
http.Error(w, "no message with id "+messageIDStr, http.StatusNotFound)
return
}
if err != nil {
fmt.Fprintf(w, "\n\ncouldn't fetch message: %+v", err)
http.Error(w, "couldn't fetch message", http.StatusInternalServerError)
return
}
priorCacheKey := "prior-" + messageIDStr
priorMessages, err := h.FetchAndCacheList(r, priorCacheKey, func() ([]database.Message, error) {
return h.DB.PriorMessages(message.Room, message.At, limit)
})
if err != nil && err != sql.ErrNoRows {
fmt.Fprintf(w, "\n\ncouldn't fetch prior messages: %+v", err)
http.Error(w, "couldn't fetch prior messages", http.StatusInternalServerError)
return
}
subsequentCacheKey := "subsequent-" + messageIDStr
subsequentMessages, err := h.FetchAndCacheList(r, subsequentCacheKey, func() ([]database.Message, error) {
return h.DB.SubsequentMessages(message.Room, message.At, limit)
})
if err != nil && err != sql.ErrNoRows {
fmt.Fprintf(w, "\n\ncouldn't fetch subsequent messages: %+v", err)
http.Error(w, "couldn't fetch subsequent messages", http.StatusInternalServerError)
return
}
data := &template.ShowTemplateData{
PriorMessages: priorMessages,
Message: *message,
SubsequentMessages: subsequentMessages,
Rooms: h.AllRooms(),
CurrentRoom: message.Room,
}
if err := template.ShowTemplate.Execute(w, data); err != nil {
fmt.Fprintf(w, "\n\n%+v", err)
}
}
// Pulls the limit query parameter from the request
// and returns default of 20 if blank or non-integer.
func resultsLimit(r *http.Request) int {
values := r.URL.Query()["limit"]
if len(values) == 0 {
return 20
}
limitStr := values[0]
if limitStr == "" {
return 20
}
limit, err := strconv.Atoi(limitStr)
if err != nil {
LogWithRequestID(r, fmt.Sprintf("Bad limit '%s': %+v", limitStr, err))
return 20
}
// Cap limit at a reasonable number for the DB.
if limit > 100 {
return 100
}
return limit
}