blob: 68e900206e7610c96582975549456740bfe3249b [file] [log] [blame]
Sergiusz Bazanskia8854882020-01-05 00:34:38 +01001package irc
2
3import (
4 "context"
5 "fmt"
6
7 "github.com/golang/glog"
8)
9
10// Control: send a message to IRC.
11func (m *Manager) SendMessage(user, text string) error {
12 done := make(chan error)
13 m.ctrl <- &control{
14 message: &controlMessage{
15 from: user,
16 message: text,
17 done: done,
18 },
19 }
20 return <-done
21}
22
23// Control: subscribe to notifiactions.
24func (m *Manager) Subscribe(c chan *Notification) {
25 m.ctrl <- &control{
26 subscribe: &controlSubscribe{
27 c: c,
28 },
29 }
30}
31
32// control message from owner. Only one member can be set.
33type control struct {
34 // message needs to be send to IRC
35 message *controlMessage
36 // a new subscription channel for notifications is presented
37 subscribe *controlSubscribe
38}
39
40// controlMessage is a request to send a message to IRC as a given user
41type controlMessage struct {
42 // user name (native to application)
43 from string
44 // plaintext message
45 message string
46 // channel that will be sent nil or an error when the message has been
47 // succesfully sent or an error occured
48 done chan error
49}
50
51// controlSubscribe is a request to send notifications to a given channel
52type controlSubscribe struct {
53 c chan *Notification
54}
55
56// doctrl processes a given control message.
57func (m *Manager) doctrl(ctx context.Context, c *control) {
58 switch {
59
60 case c.message != nil:
61 // Send a message to IRC.
62
63 // Find a relevant connection, or make one.
64 conn, err := m.getconn(ctx, c.message.from)
65 if err != nil {
66 // Do not attempt to redeliver bans.
67 if err == errBanned {
68 c.message.done <- nil
69 } else {
70 c.message.done <- fmt.Errorf("getting connection: %v", err)
71 }
72 return
73 }
74
75 // Route message to connection.
76 conn.Say(c.message)
77
78 case c.subscribe != nil:
79 // Subscribe to notifications.
80 m.subscribers[c.subscribe.c] = true
81
82 default:
83 glog.Errorf("unhandled control %+v", c)
84 }
85}