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