This repository has been archived by the owner on Oct 28, 2021. It is now read-only.
forked from Rhymen/go-whatsapp
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
conn.go
259 lines (226 loc) · 5.27 KB
/
conn.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//Package whatsapp provides a developer API to interact with the WhatsAppWeb-Servers.
package whatsapp
import (
"fmt"
"net/http"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
log "maunium.net/go/maulogger/v2"
)
type metric byte
const (
debugLog metric = iota + 1
queryResume
queryReceipt
queryMedia
queryChat
queryContacts
queryMessages
presence
presenceSubscribe
group
read
chat
received
pic
status
message
queryActions
block
queryGroup
queryPreview
queryEmoji
queryMessageInfo
spam
querySearch
queryIdentity
queryUrl
profile
contact
queryVcard
queryStatus
queryStatusUpdate
privacyStatus
queryLiveLocations
liveLocation
queryVname
queryLabels
call
queryCall
queryQuickReplies
)
type flag byte
const (
ignore flag = 1 << (7 - iota)
ackRequest
available
notAvailable
expires
skipOffline
)
/*
Conn is created by NewConn. Interacting with the initialized Conn is the main way of interacting with our package.
It holds all necessary information to make the package work internally.
*/
type Conn struct {
log log.Logger
ws *websocketWrapper
listener *listenerWrapper
atw *adminTestWait
atwLock sync.Mutex
connected bool
adminInited bool
loggedIn bool
session *Session
sessionLock uint32
sessionWait sync.WaitGroup
handler []Handler
msgCount int
msgTimeout time.Duration
Store *Store
ServerLastSeen time.Time
timeTag string // last 3 digits obtained after a successful login takeover
longClientName string
shortClientName string
clientVersion string
loginSessionLock sync.RWMutex
Proxy func(*http.Request) (*url.URL, error)
CountTimeoutHook func(wsKeepaliveErrorCount int)
AdminTestHook func(err error)
}
type Options struct {
Proxy func(*http.Request) (*url.URL, error)
Timeout time.Duration
Handler []Handler
ShortClientName string
LongClientName string
ClientVersion string
Store *Store
Log log.Logger
}
func NewConn(opt *Options) *Conn {
if opt == nil {
panic(ErrOptionsNotProvided)
}
if opt.Log == nil {
opt.Log = log.DefaultLogger
}
if opt.Handler == nil {
opt.Handler = make([]Handler, 0)
}
if opt.Store == nil {
opt.Store = newStore()
}
wac := &Conn{
log: opt.Log,
handler: opt.Handler,
msgCount: 0,
msgTimeout: opt.Timeout,
Store: opt.Store,
Proxy: opt.Proxy,
longClientName: "github.com/Rhymen/go-whatsapp",
shortClientName: "go-whatsapp",
clientVersion: "0.1.0",
}
if len(opt.ShortClientName) != 0 {
wac.shortClientName = opt.ShortClientName
}
if len(opt.LongClientName) != 0 {
wac.longClientName = opt.LongClientName
}
if len(opt.ClientVersion) != 0 {
wac.clientVersion = opt.ClientVersion
}
return wac
}
func (wac *Conn) connect() (err error) {
if wac.connected {
return ErrAlreadyConnected
}
wac.connected = true
defer func() { // set connected to false on error
if err != nil {
wac.connected = false
}
}()
dialer := &websocket.Dialer{
ReadBufferSize: 0,
WriteBufferSize: 0,
HandshakeTimeout: wac.msgTimeout,
Proxy: wac.Proxy,
}
headers := http.Header{"Origin": []string{"https://web.whatsapp.com"}}
wac.log.Debugln("Dialing wss://web.whatsapp.com/ws")
wsConn, _, err := dialer.Dial("wss://web.whatsapp.com/ws", headers)
if err != nil {
return fmt.Errorf("couldn't dial whatsapp web websocket: %w", err)
}
wsConn.SetCloseHandler(func(code int, text string) error {
wac.log.Debugfln("Close handler called with %d/%s", code, text)
// from default CloseHandler
message := websocket.FormatCloseMessage(code, "")
err := wsConn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second))
// our close handling
wac.log.Debugfln("Disconnecting local websocket in close handler")
disconnectErr := wac.Disconnect()
if disconnectErr != nil {
wac.log.Debugln("Disconnection returned error:", err)
}
wac.log.Debugfln("Sending connection close error to handler")
wac.handle(&ErrConnectionClosed{Code: code, Text: text})
return err
})
ws := newWebsocketWrapper(wsConn)
wac.ws = ws
if wac.listener == nil {
wac.listener = newListenerWrapper()
} else {
wac.listener.onReconnect()
}
ws.Add(2)
go wac.readPump(ws)
go wac.keepAlive(ws, 21000, 30000)
wac.loggedIn = false
wac.adminInited = false
wac.log.Debugln("Successfully connected to websocket")
return nil
}
func (wac *Conn) Disconnect() error {
if !wac.connected {
return ErrNotConnected
}
wac.log.Debugfln("Disconnecting websocket")
wac.connected = false
wac.loggedIn = false
wac.adminInited = false
ws := wac.ws
ws.cancel()
ws.Wait()
var err error
if ws.conn != nil {
err = ws.conn.Close()
}
if wac.ws == ws {
wac.ws = nil
wac.log.Debugfln("Websocket disconnection complete")
} else {
wac.log.Warnln("The current websocket isn't the one being disconnected?!")
}
return err
}
func (wac *Conn) IsLoginInProgress() bool {
return wac.sessionLock == 1
}
func (wac *Conn) WaitForLogin() {
wac.sessionWait.Wait()
}
// IsConnected returns whether the server connection is established or not
func (wac *Conn) IsConnected() bool {
return wac.connected
}
//IsLoggedIn returns whether the you are logged in or not
func (wac *Conn) IsLoggedIn() bool {
return wac.loggedIn
}