1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "bufio"
|
---|
5 | "fmt"
|
---|
6 | "io"
|
---|
7 | "os"
|
---|
8 | "path/filepath"
|
---|
9 | "strings"
|
---|
10 | "time"
|
---|
11 |
|
---|
12 | "git.sr.ht/~sircmpwn/go-bare"
|
---|
13 | "gopkg.in/irc.v3"
|
---|
14 | )
|
---|
15 |
|
---|
16 | const fsMessageStoreMaxTries = 100
|
---|
17 |
|
---|
18 | var escapeFilename = strings.NewReplacer("/", "-", "\\", "-")
|
---|
19 |
|
---|
20 | type date struct {
|
---|
21 | Year, Month, Day int
|
---|
22 | }
|
---|
23 |
|
---|
24 | func newDate(t time.Time) date {
|
---|
25 | year, month, day := t.Date()
|
---|
26 | return date{year, int(month), day}
|
---|
27 | }
|
---|
28 |
|
---|
29 | func (d date) Time() time.Time {
|
---|
30 | return time.Date(d.Year, time.Month(d.Month), d.Day, 0, 0, 0, 0, time.Local)
|
---|
31 | }
|
---|
32 |
|
---|
33 | type fsMsgID struct {
|
---|
34 | Date date
|
---|
35 | Offset bare.Int
|
---|
36 | }
|
---|
37 |
|
---|
38 | func (fsMsgID) msgIDType() msgIDType {
|
---|
39 | return msgIDFS
|
---|
40 | }
|
---|
41 |
|
---|
42 | func parseFSMsgID(s string) (netID int64, entity string, t time.Time, offset int64, err error) {
|
---|
43 | var id fsMsgID
|
---|
44 | netID, entity, err = parseMsgID(s, &id)
|
---|
45 | if err != nil {
|
---|
46 | return 0, "", time.Time{}, 0, err
|
---|
47 | }
|
---|
48 | return netID, entity, id.Date.Time(), int64(id.Offset), nil
|
---|
49 | }
|
---|
50 |
|
---|
51 | func formatFSMsgID(netID int64, entity string, t time.Time, offset int64) string {
|
---|
52 | id := fsMsgID{
|
---|
53 | Date: newDate(t),
|
---|
54 | Offset: bare.Int(offset),
|
---|
55 | }
|
---|
56 | return formatMsgID(netID, entity, &id)
|
---|
57 | }
|
---|
58 |
|
---|
59 | // fsMessageStore is a per-user on-disk store for IRC messages.
|
---|
60 | type fsMessageStore struct {
|
---|
61 | root string
|
---|
62 |
|
---|
63 | files map[string]*os.File // indexed by entity
|
---|
64 | }
|
---|
65 |
|
---|
66 | var _ messageStore = (*fsMessageStore)(nil)
|
---|
67 | var _ chatHistoryMessageStore = (*fsMessageStore)(nil)
|
---|
68 |
|
---|
69 | func newFSMessageStore(root, username string) *fsMessageStore {
|
---|
70 | return &fsMessageStore{
|
---|
71 | root: filepath.Join(root, escapeFilename.Replace(username)),
|
---|
72 | files: make(map[string]*os.File),
|
---|
73 | }
|
---|
74 | }
|
---|
75 |
|
---|
76 | func (ms *fsMessageStore) logPath(network *network, entity string, t time.Time) string {
|
---|
77 | year, month, day := t.Date()
|
---|
78 | filename := fmt.Sprintf("%04d-%02d-%02d.log", year, month, day)
|
---|
79 | return filepath.Join(ms.root, escapeFilename.Replace(network.GetName()), escapeFilename.Replace(entity), filename)
|
---|
80 | }
|
---|
81 |
|
---|
82 | // nextMsgID queries the message ID for the next message to be written to f.
|
---|
83 | func nextFSMsgID(network *network, entity string, t time.Time, f *os.File) (string, error) {
|
---|
84 | offset, err := f.Seek(0, io.SeekEnd)
|
---|
85 | if err != nil {
|
---|
86 | return "", fmt.Errorf("failed to query next FS message ID: %v", err)
|
---|
87 | }
|
---|
88 | return formatFSMsgID(network.ID, entity, t, offset), nil
|
---|
89 | }
|
---|
90 |
|
---|
91 | func (ms *fsMessageStore) LastMsgID(network *network, entity string, t time.Time) (string, error) {
|
---|
92 | p := ms.logPath(network, entity, t)
|
---|
93 | fi, err := os.Stat(p)
|
---|
94 | if os.IsNotExist(err) {
|
---|
95 | return formatFSMsgID(network.ID, entity, t, -1), nil
|
---|
96 | } else if err != nil {
|
---|
97 | return "", fmt.Errorf("failed to query last FS message ID: %v", err)
|
---|
98 | }
|
---|
99 | return formatFSMsgID(network.ID, entity, t, fi.Size()-1), nil
|
---|
100 | }
|
---|
101 |
|
---|
102 | func (ms *fsMessageStore) Append(network *network, entity string, msg *irc.Message) (string, error) {
|
---|
103 | s := formatMessage(msg)
|
---|
104 | if s == "" {
|
---|
105 | return "", nil
|
---|
106 | }
|
---|
107 |
|
---|
108 | var t time.Time
|
---|
109 | if tag, ok := msg.Tags["time"]; ok {
|
---|
110 | var err error
|
---|
111 | t, err = time.Parse(serverTimeLayout, string(tag))
|
---|
112 | if err != nil {
|
---|
113 | return "", fmt.Errorf("failed to parse message time tag: %v", err)
|
---|
114 | }
|
---|
115 | t = t.In(time.Local)
|
---|
116 | } else {
|
---|
117 | t = time.Now()
|
---|
118 | }
|
---|
119 |
|
---|
120 | // TODO: enforce maximum open file handles (LRU cache of file handles)
|
---|
121 | f := ms.files[entity]
|
---|
122 |
|
---|
123 | // TODO: handle non-monotonic clock behaviour
|
---|
124 | path := ms.logPath(network, entity, t)
|
---|
125 | if f == nil || f.Name() != path {
|
---|
126 | if f != nil {
|
---|
127 | f.Close()
|
---|
128 | }
|
---|
129 |
|
---|
130 | dir := filepath.Dir(path)
|
---|
131 | if err := os.MkdirAll(dir, 0700); err != nil {
|
---|
132 | return "", fmt.Errorf("failed to create message logs directory %q: %v", dir, err)
|
---|
133 | }
|
---|
134 |
|
---|
135 | var err error
|
---|
136 | f, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
|
---|
137 | if err != nil {
|
---|
138 | return "", fmt.Errorf("failed to open message log file %q: %v", path, err)
|
---|
139 | }
|
---|
140 |
|
---|
141 | ms.files[entity] = f
|
---|
142 | }
|
---|
143 |
|
---|
144 | msgID, err := nextFSMsgID(network, entity, t, f)
|
---|
145 | if err != nil {
|
---|
146 | return "", fmt.Errorf("failed to generate message ID: %v", err)
|
---|
147 | }
|
---|
148 |
|
---|
149 | _, err = fmt.Fprintf(f, "[%02d:%02d:%02d] %s\n", t.Hour(), t.Minute(), t.Second(), s)
|
---|
150 | if err != nil {
|
---|
151 | return "", fmt.Errorf("failed to log message to %q: %v", f.Name(), err)
|
---|
152 | }
|
---|
153 |
|
---|
154 | return msgID, nil
|
---|
155 | }
|
---|
156 |
|
---|
157 | func (ms *fsMessageStore) Close() error {
|
---|
158 | var closeErr error
|
---|
159 | for _, f := range ms.files {
|
---|
160 | if err := f.Close(); err != nil {
|
---|
161 | closeErr = fmt.Errorf("failed to close message store: %v", err)
|
---|
162 | }
|
---|
163 | }
|
---|
164 | return closeErr
|
---|
165 | }
|
---|
166 |
|
---|
167 | // formatMessage formats a message log line. It assumes a well-formed IRC
|
---|
168 | // message.
|
---|
169 | func formatMessage(msg *irc.Message) string {
|
---|
170 | switch strings.ToUpper(msg.Command) {
|
---|
171 | case "NICK":
|
---|
172 | return fmt.Sprintf("*** %s is now known as %s", msg.Prefix.Name, msg.Params[0])
|
---|
173 | case "JOIN":
|
---|
174 | return fmt.Sprintf("*** Joins: %s (%s@%s)", msg.Prefix.Name, msg.Prefix.User, msg.Prefix.Host)
|
---|
175 | case "PART":
|
---|
176 | var reason string
|
---|
177 | if len(msg.Params) > 1 {
|
---|
178 | reason = msg.Params[1]
|
---|
179 | }
|
---|
180 | return fmt.Sprintf("*** Parts: %s (%s@%s) (%s)", msg.Prefix.Name, msg.Prefix.User, msg.Prefix.Host, reason)
|
---|
181 | case "KICK":
|
---|
182 | nick := msg.Params[1]
|
---|
183 | var reason string
|
---|
184 | if len(msg.Params) > 2 {
|
---|
185 | reason = msg.Params[2]
|
---|
186 | }
|
---|
187 | return fmt.Sprintf("*** %s was kicked by %s (%s)", nick, msg.Prefix.Name, reason)
|
---|
188 | case "QUIT":
|
---|
189 | var reason string
|
---|
190 | if len(msg.Params) > 0 {
|
---|
191 | reason = msg.Params[0]
|
---|
192 | }
|
---|
193 | return fmt.Sprintf("*** Quits: %s (%s@%s) (%s)", msg.Prefix.Name, msg.Prefix.User, msg.Prefix.Host, reason)
|
---|
194 | case "TOPIC":
|
---|
195 | var topic string
|
---|
196 | if len(msg.Params) > 1 {
|
---|
197 | topic = msg.Params[1]
|
---|
198 | }
|
---|
199 | return fmt.Sprintf("*** %s changes topic to '%s'", msg.Prefix.Name, topic)
|
---|
200 | case "MODE":
|
---|
201 | return fmt.Sprintf("*** %s sets mode: %s", msg.Prefix.Name, strings.Join(msg.Params[1:], " "))
|
---|
202 | case "NOTICE":
|
---|
203 | return fmt.Sprintf("-%s- %s", msg.Prefix.Name, msg.Params[1])
|
---|
204 | case "PRIVMSG":
|
---|
205 | if cmd, params, ok := parseCTCPMessage(msg); ok && cmd == "ACTION" {
|
---|
206 | return fmt.Sprintf("* %s %s", msg.Prefix.Name, params)
|
---|
207 | } else {
|
---|
208 | return fmt.Sprintf("<%s> %s", msg.Prefix.Name, msg.Params[1])
|
---|
209 | }
|
---|
210 | default:
|
---|
211 | return ""
|
---|
212 | }
|
---|
213 | }
|
---|
214 |
|
---|
215 | func parseMessage(line, entity string, ref time.Time) (*irc.Message, time.Time, error) {
|
---|
216 | var hour, minute, second int
|
---|
217 | _, err := fmt.Sscanf(line, "[%02d:%02d:%02d] ", &hour, &minute, &second)
|
---|
218 | if err != nil {
|
---|
219 | return nil, time.Time{}, fmt.Errorf("malformed timestamp prefix: %v", err)
|
---|
220 | }
|
---|
221 | line = line[11:]
|
---|
222 |
|
---|
223 | var cmd, sender, text string
|
---|
224 | if strings.HasPrefix(line, "<") {
|
---|
225 | cmd = "PRIVMSG"
|
---|
226 | parts := strings.SplitN(line[1:], "> ", 2)
|
---|
227 | if len(parts) != 2 {
|
---|
228 | return nil, time.Time{}, nil
|
---|
229 | }
|
---|
230 | sender, text = parts[0], parts[1]
|
---|
231 | } else if strings.HasPrefix(line, "-") {
|
---|
232 | cmd = "NOTICE"
|
---|
233 | parts := strings.SplitN(line[1:], "- ", 2)
|
---|
234 | if len(parts) != 2 {
|
---|
235 | return nil, time.Time{}, nil
|
---|
236 | }
|
---|
237 | sender, text = parts[0], parts[1]
|
---|
238 | } else if strings.HasPrefix(line, "* ") {
|
---|
239 | cmd = "PRIVMSG"
|
---|
240 | parts := strings.SplitN(line[2:], " ", 2)
|
---|
241 | if len(parts) != 2 {
|
---|
242 | return nil, time.Time{}, nil
|
---|
243 | }
|
---|
244 | sender, text = parts[0], "\x01ACTION "+parts[1]+"\x01"
|
---|
245 | } else {
|
---|
246 | return nil, time.Time{}, nil
|
---|
247 | }
|
---|
248 |
|
---|
249 | year, month, day := ref.Date()
|
---|
250 | t := time.Date(year, month, day, hour, minute, second, 0, time.Local)
|
---|
251 |
|
---|
252 | msg := &irc.Message{
|
---|
253 | Tags: map[string]irc.TagValue{
|
---|
254 | "time": irc.TagValue(t.UTC().Format(serverTimeLayout)),
|
---|
255 | },
|
---|
256 | Prefix: &irc.Prefix{Name: sender},
|
---|
257 | Command: cmd,
|
---|
258 | Params: []string{entity, text},
|
---|
259 | }
|
---|
260 | return msg, t, nil
|
---|
261 | }
|
---|
262 |
|
---|
263 | func (ms *fsMessageStore) parseMessagesBefore(network *network, entity string, ref time.Time, end time.Time, limit int, afterOffset int64) ([]*irc.Message, error) {
|
---|
264 | path := ms.logPath(network, entity, ref)
|
---|
265 | f, err := os.Open(path)
|
---|
266 | if err != nil {
|
---|
267 | if os.IsNotExist(err) {
|
---|
268 | return nil, nil
|
---|
269 | }
|
---|
270 | return nil, fmt.Errorf("failed to parse messages before ref: %v", err)
|
---|
271 | }
|
---|
272 | defer f.Close()
|
---|
273 |
|
---|
274 | historyRing := make([]*irc.Message, limit)
|
---|
275 | cur := 0
|
---|
276 |
|
---|
277 | sc := bufio.NewScanner(f)
|
---|
278 |
|
---|
279 | if afterOffset >= 0 {
|
---|
280 | if _, err := f.Seek(afterOffset, io.SeekStart); err != nil {
|
---|
281 | return nil, nil
|
---|
282 | }
|
---|
283 | sc.Scan() // skip till next newline
|
---|
284 | }
|
---|
285 |
|
---|
286 | for sc.Scan() {
|
---|
287 | msg, t, err := parseMessage(sc.Text(), entity, ref)
|
---|
288 | if err != nil {
|
---|
289 | return nil, err
|
---|
290 | } else if msg == nil || !t.After(end) {
|
---|
291 | continue
|
---|
292 | } else if !t.Before(ref) {
|
---|
293 | break
|
---|
294 | }
|
---|
295 |
|
---|
296 | historyRing[cur%limit] = msg
|
---|
297 | cur++
|
---|
298 | }
|
---|
299 | if sc.Err() != nil {
|
---|
300 | return nil, fmt.Errorf("failed to parse messages before ref: scanner error: %v", sc.Err())
|
---|
301 | }
|
---|
302 |
|
---|
303 | n := limit
|
---|
304 | if cur < limit {
|
---|
305 | n = cur
|
---|
306 | }
|
---|
307 | start := (cur - n + limit) % limit
|
---|
308 |
|
---|
309 | if start+n <= limit { // ring doesnt wrap
|
---|
310 | return historyRing[start : start+n], nil
|
---|
311 | } else { // ring wraps
|
---|
312 | history := make([]*irc.Message, n)
|
---|
313 | r := copy(history, historyRing[start:])
|
---|
314 | copy(history[r:], historyRing[:n-r])
|
---|
315 | return history, nil
|
---|
316 | }
|
---|
317 | }
|
---|
318 |
|
---|
319 | func (ms *fsMessageStore) parseMessagesAfter(network *network, entity string, ref time.Time, end time.Time, limit int) ([]*irc.Message, error) {
|
---|
320 | path := ms.logPath(network, entity, ref)
|
---|
321 | f, err := os.Open(path)
|
---|
322 | if err != nil {
|
---|
323 | if os.IsNotExist(err) {
|
---|
324 | return nil, nil
|
---|
325 | }
|
---|
326 | return nil, fmt.Errorf("failed to parse messages after ref: %v", err)
|
---|
327 | }
|
---|
328 | defer f.Close()
|
---|
329 |
|
---|
330 | var history []*irc.Message
|
---|
331 | sc := bufio.NewScanner(f)
|
---|
332 | for sc.Scan() && len(history) < limit {
|
---|
333 | msg, t, err := parseMessage(sc.Text(), entity, ref)
|
---|
334 | if err != nil {
|
---|
335 | return nil, err
|
---|
336 | } else if msg == nil || !t.After(ref) {
|
---|
337 | continue
|
---|
338 | } else if !t.Before(end) {
|
---|
339 | break
|
---|
340 | }
|
---|
341 |
|
---|
342 | history = append(history, msg)
|
---|
343 | }
|
---|
344 | if sc.Err() != nil {
|
---|
345 | return nil, fmt.Errorf("failed to parse messages after ref: scanner error: %v", sc.Err())
|
---|
346 | }
|
---|
347 |
|
---|
348 | return history, nil
|
---|
349 | }
|
---|
350 |
|
---|
351 | func (ms *fsMessageStore) LoadBeforeTime(network *network, entity string, start time.Time, end time.Time, limit int) ([]*irc.Message, error) {
|
---|
352 | history := make([]*irc.Message, limit)
|
---|
353 | remaining := limit
|
---|
354 | tries := 0
|
---|
355 | for remaining > 0 && tries < fsMessageStoreMaxTries && end.Before(start) {
|
---|
356 | buf, err := ms.parseMessagesBefore(network, entity, start, end, remaining, -1)
|
---|
357 | if err != nil {
|
---|
358 | return nil, err
|
---|
359 | }
|
---|
360 | if len(buf) == 0 {
|
---|
361 | tries++
|
---|
362 | } else {
|
---|
363 | tries = 0
|
---|
364 | }
|
---|
365 | copy(history[remaining-len(buf):], buf)
|
---|
366 | remaining -= len(buf)
|
---|
367 | year, month, day := start.Date()
|
---|
368 | start = time.Date(year, month, day, 0, 0, 0, 0, start.Location()).Add(-1)
|
---|
369 | }
|
---|
370 |
|
---|
371 | return history[remaining:], nil
|
---|
372 | }
|
---|
373 |
|
---|
374 | func (ms *fsMessageStore) LoadAfterTime(network *network, entity string, start time.Time, end time.Time, limit int) ([]*irc.Message, error) {
|
---|
375 | var history []*irc.Message
|
---|
376 | remaining := limit
|
---|
377 | tries := 0
|
---|
378 | for remaining > 0 && tries < fsMessageStoreMaxTries && start.Before(end) {
|
---|
379 | buf, err := ms.parseMessagesAfter(network, entity, start, end, remaining)
|
---|
380 | if err != nil {
|
---|
381 | return nil, err
|
---|
382 | }
|
---|
383 | if len(buf) == 0 {
|
---|
384 | tries++
|
---|
385 | } else {
|
---|
386 | tries = 0
|
---|
387 | }
|
---|
388 | history = append(history, buf...)
|
---|
389 | remaining -= len(buf)
|
---|
390 | year, month, day := start.Date()
|
---|
391 | start = time.Date(year, month, day+1, 0, 0, 0, 0, start.Location())
|
---|
392 | }
|
---|
393 | return history, nil
|
---|
394 | }
|
---|
395 |
|
---|
396 | func truncateDay(t time.Time) time.Time {
|
---|
397 | year, month, day := t.Date()
|
---|
398 | return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
|
---|
399 | }
|
---|
400 |
|
---|
401 | func (ms *fsMessageStore) LoadLatestID(network *network, entity, id string, limit int) ([]*irc.Message, error) {
|
---|
402 | var afterTime time.Time
|
---|
403 | var afterOffset int64
|
---|
404 | if id != "" {
|
---|
405 | var idNet int64
|
---|
406 | var idEntity string
|
---|
407 | var err error
|
---|
408 | idNet, idEntity, afterTime, afterOffset, err = parseFSMsgID(id)
|
---|
409 | if err != nil {
|
---|
410 | return nil, err
|
---|
411 | }
|
---|
412 | if idNet != network.ID || idEntity != entity {
|
---|
413 | return nil, fmt.Errorf("cannot find message ID: message ID doesn't match network/entity")
|
---|
414 | }
|
---|
415 | }
|
---|
416 |
|
---|
417 | history := make([]*irc.Message, limit)
|
---|
418 | t := time.Now()
|
---|
419 | remaining := limit
|
---|
420 | tries := 0
|
---|
421 | for remaining > 0 && tries < fsMessageStoreMaxTries && !truncateDay(t).Before(afterTime) {
|
---|
422 | var offset int64 = -1
|
---|
423 | if afterOffset >= 0 && truncateDay(t).Equal(afterTime) {
|
---|
424 | offset = afterOffset
|
---|
425 | }
|
---|
426 |
|
---|
427 | buf, err := ms.parseMessagesBefore(network, entity, t, time.Time{}, remaining, offset)
|
---|
428 | if err != nil {
|
---|
429 | return nil, err
|
---|
430 | }
|
---|
431 | if len(buf) == 0 {
|
---|
432 | tries++
|
---|
433 | } else {
|
---|
434 | tries = 0
|
---|
435 | }
|
---|
436 | copy(history[remaining-len(buf):], buf)
|
---|
437 | remaining -= len(buf)
|
---|
438 | year, month, day := t.Date()
|
---|
439 | t = time.Date(year, month, day, 0, 0, 0, 0, t.Location()).Add(-1)
|
---|
440 | }
|
---|
441 |
|
---|
442 | return history[remaining:], nil
|
---|
443 | }
|
---|