summaryrefslogtreecommitdiff
path: root/room.go
blob: a7c2ad0c4598a17f17605dd32840c58a855986c3 (plain)
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
package main

import (
	"fmt"
	"log"
	"strings"

	"dim13.org/bot/internal/flood"
	"dim13.org/bot/internal/href"
	"dim13.org/bot/internal/re"
	irc "github.com/fluffle/goirc/client"
	lru "github.com/hashicorp/golang-lru"
)

type Room struct {
	room   string
	last   *lru.Cache
	titles *lru.Cache
}

func newRoom(room string, sz int) *Room {
	last, _ := lru.New(sz)
	titles, _ := lru.New(sz)
	return &Room{room: room, last: last, titles: titles}
}

func (r *Room) Handle(conn *irc.Conn, line *irc.Line) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("panic", r)
		}
	}()
	t := line.Text()
	switch {
	case line.Nick == conn.Me().Nick:
		// ignore self
	case flood.Is(t):
		log.Println("flood", line.Nick)
		conn.Kick(r.room, line.Nick)
	case strings.HasPrefix(t, "s"):
		global := strings.HasSuffix(t, "g")
		if tofix, ok := r.last.Get(line.Nick); ok {
			fixed, err := re.Replace(tofix.(string), t[1:], global)
			if err == nil && fixed != tofix {
				log.Println("regexp", t)
				fmt.Fprintf(newNotify(conn, line.Target()), "%v meant to say: %s", line.Nick, fixed)
				return
			}

		}
		fallthrough
	default:
		for _, v := range href.Links(t) {
			title, ok := r.titles.Get(v)
			if !ok {
				var err error
				title, err = href.Title(v)
				if err != nil {
					log.Println(v, err)
				}
				r.titles.Add(v, title)
			}
			if title != "" {
				w := newNotify(conn, line.Target())
				if ok {
					fmt.Fprintf(w, "Title: %v (cached)", title)
				} else {
					fmt.Fprintf(w, "Title: %v", title)
				}
			}
		}
		r.last.Add(line.Nick, t)
	}
}