Debian Codegraph @

websocket.go

raw symbols SCIP
1 package slack
2
3 import (
4 "net/url"
5 "sync"
6 "time"
7
8 "github.com/gorilla/websocket"
9 )
10
11 const (
12 // MaxMessageTextLength is the current maximum message length in number of characters as defined here
13 // https://api.slack.com/rtm#limits
14 MaxMessageTextLength = 4000
15 )
16
17 // RTM represents a managed websocket connection. It also supports
18 // all the methods of the `Client` type.
19 //
20 // Create this element with Client's NewRTM() or NewRTMWithOptions(*RTMOptions)
21 type RTM struct {
22 // Client is the main API, embedded
23 Client
24
25 idGen IDGenerator
26 pingInterval time.Duration
27 pingDeadman *time.Timer
28
29 // Connection life-cycle
30 conn *websocket.Conn
31 IncomingEvents chan RTMEvent
32 outgoingMessages chan OutgoingMessage
33 killChannel chan bool
34 disconnected chan struct{}
35 disconnectedm *sync.Once
36 forcePing chan bool
37
38 // UserDetails upon connection
39 info *Info
40
41 // useRTMStart should be set to true if you want to use
42 // rtm.start to connect to Slack, otherwise it will use
43 // rtm.connect
44 useRTMStart bool
45
46 // dialer is a gorilla/websocket Dialer. If nil, use the default
47 // Dialer.
48 dialer *websocket.Dialer
49
50 // mu is mutex used to prevent RTM connection race conditions
51 mu *sync.Mutex
52
53 // connParams is a map of flags for connection parameters.
54 connParams url.Values
55 }
56
57 // signal that we are disconnected by closing the channel.
58 // protect it with a mutex to ensure it only happens once.
59 func (rtm *RTM) disconnect() {
60 rtm.disconnectedm.Do(func() {
61 close(rtm.disconnected)
62 })
63 }
64
65 // Disconnect and wait, blocking until a successful disconnection.
66 func (rtm *RTM) Disconnect() error {
67 // always push into the kill channel when invoked,
68 // this lets the ManagedConnection() function properly clean up.
69 // if the buffer is full then just continue on.
70 select {
71 case rtm.killChannel <- true:
72 return nil
73 case <-rtm.disconnected:
74 return ErrAlreadyDisconnected
75 }
76 }
77
78 // GetInfo returns the info structure received when calling
79 // "startrtm", holding metadata needed to implement a full
80 // chat client. It will be non-nil after a call to StartRTM().
81 func (rtm *RTM) GetInfo() *Info {
82 return rtm.info
83 }
84
85 // SendMessage submits a simple message through the websocket. For
86 // more complicated messages, use `rtm.PostMessage` with a complete
87 // struct describing your attachments and all.
88 func (rtm *RTM) SendMessage(msg *OutgoingMessage) {
89 if msg == nil {
90 rtm.Debugln("Error: Attempted to SendMessage(nil)")
91 return
92 }
93
94 rtm.outgoingMessages <- *msg
95 }
96
97 func (rtm *RTM) resetDeadman() {
98 rtm.pingDeadman.Reset(deadmanDuration(rtm.pingInterval))
99 }
100
101 func deadmanDuration(d time.Duration) time.Duration {
102 return d * 4
103 }