Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 1 | package irc |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/golang/glog" |
| 9 | ) |
| 10 | |
| 11 | var ( |
| 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 Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 17 | func (m *Manager) getconn(ctx context.Context, userTelegram string) (*ircconn, error) { |
Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 18 | // Is the user shitlisted? |
Michal Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 19 | if t, ok := m.shitlist[userTelegram]; ok && time.Now().Before(t) { |
Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 20 | return nil, errBanned |
| 21 | } |
| 22 | // Do we already have a connection? |
Michal Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 23 | c, ok := m.conns[userTelegram] |
Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 24 | 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 Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 49 | return m.newconn(ctx, userTelegram, false) |
Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 50 | } |
| 51 | |
| 52 | // newconn creates a new IRC connection as a given user, and saves it to the |
| 53 | // conns map. |
Michal Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 54 | func (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 Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
Michal Zagorski | 5b1aa13 | 2020-03-01 17:05:05 +0100 | [diff] [blame] | 59 | m.conns[userTelegram] = c |
Sergiusz Bazanski | a885488 | 2020-01-05 00:34:38 +0100 | [diff] [blame] | 60 | |
| 61 | go c.Run(m.runctx) |
| 62 | |
| 63 | return c, nil |
| 64 | } |