blob: b578f0d54675b340eebabb3b6fd178309bc35bad [file] [log] [blame]
Sergiusz Bazanskia8854882020-01-05 00:34:38 +01001package irc
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/golang/glog"
9)
10
11var (
12 errBanned = fmt.Errorf("user is shitlisted")
13)
14
15// getconn either gets a connection by username, or creates a new one (after
16// evicting the least recently used connection).
Michal Zagorski5b1aa132020-03-01 17:05:05 +010017func (m *Manager) getconn(ctx context.Context, userTelegram string) (*ircconn, error) {
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010018 // Is the user shitlisted?
Michal Zagorski5b1aa132020-03-01 17:05:05 +010019 if t, ok := m.shitlist[userTelegram]; ok && time.Now().Before(t) {
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010020 return nil, errBanned
21 }
22 // Do we already have a connection?
Michal Zagorski5b1aa132020-03-01 17:05:05 +010023 c, ok := m.conns[userTelegram]
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010024 if ok {
25 // Bump and return.
26 c.last = time.Now()
27 return c, nil
28 }
29
30 // Are we at the limit of allowed connections?
31 if len(m.conns) >= m.max {
32 // Evict least recently used
33 evict := ""
34 lru := time.Now()
35 for _, c := range m.conns {
36 if c.last.Before(lru) {
37 evict = c.user
38 lru = c.last
39 }
40 }
41 if evict == "" {
42 glog.Exitf("could not find connection to evict, %v", m.conns)
43 }
44 m.conns[evict].Evict()
45 delete(m.conns, evict)
46 }
47
48 // Allocate new connection
Michal Zagorski5b1aa132020-03-01 17:05:05 +010049 return m.newconn(ctx, userTelegram, false)
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010050}
51
52// newconn creates a new IRC connection as a given user, and saves it to the
53// conns map.
Michal Zagorski5b1aa132020-03-01 17:05:05 +010054func (m *Manager) newconn(ctx context.Context, userTelegram string, backup bool) (*ircconn, error) {
55 c, err := NewConn(m.server, m.channel, userTelegram, backup, m.Event)
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010056 if err != nil {
57 return nil, err
58 }
Michal Zagorski5b1aa132020-03-01 17:05:05 +010059 m.conns[userTelegram] = c
Sergiusz Bazanskia8854882020-01-05 00:34:38 +010060
61 go c.Run(m.runctx)
62
63 return c, nil
64}