aboutsummaryrefslogtreecommitdiff
path: root/connector/xmpp/xmpp.go
blob: 5b1c71ae91ba885d4e4d39a878d044e00ede9a3a (plain) (blame)
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package xmpp

import (
	"time"
	//"os"
	"strings"
	"fmt"
	"crypto/tls"

	log "github.com/sirupsen/logrus"
	gxmpp "github.com/mattn/go-xmpp"

	. "git.deuxfleurs.fr/Deuxfleurs/easybridge/connector"
)

// User id format: username@server (= JID)
// OR: nickname@room_name@muc_server

// Room id format: room_name@muc_server (= MUC ID)

type XMPP struct {
	handler Handler

	connectorLoopNum int
	connected bool
	timeout int

	server string
	port int
	ssl bool
	jid string
	jid_localpart string
	password string
	nickname string

	conn *gxmpp.Client

	isMUC map[string]bool
}

func (xm *XMPP) SetHandler(h Handler) {
	xm.handler = h
}

func(xm *XMPP) Protocol() string {
	return "xmpp"
}

func (xm *XMPP) Configure(c Configuration) error {
	if xm.conn != nil {
		xm.Close()
	}

	// Parse and validate configuration
	var err error

	xm.server, err = c.GetString("server")
	if err != nil {
		return err
	}

	xm.port, err = c.GetInt("port", 5222)
	if err != nil {
		return err
	}

	xm.ssl, err = c.GetBool("ssl", true)
	if err != nil {
		return err
	}

	xm.jid, err = c.GetString("jid")
	if err != nil {
		return err
	}
	jid_parts := strings.Split(xm.jid, "@")
	if len(jid_parts) != 2 {
		return fmt.Errorf("Invalid JID: %s", xm.jid)
	}
	if jid_parts[1] != xm.server {
		return fmt.Errorf("JID %s not on server %s", xm.jid, xm.server)
	}
	xm.jid_localpart = jid_parts[0]
	xm.nickname = xm.jid_localpart

	xm.password, err = c.GetString("password")
	if err != nil {
		return err
	}

	// Try to connect
	if xm.isMUC == nil {
		xm.isMUC = make(map[string]bool)
	}

	xm.connectorLoopNum += 1
	go xm.connectLoop(xm.connectorLoopNum)

	for i := 0; i < 42; i++ {
		time.Sleep(time.Duration(1)*time.Second)
		if xm.connected {
			return nil
		}
	}
	return fmt.Errorf("Failed to connect after 42s attempting")
}

func (xm *XMPP) connectLoop(num int) {
	xm.timeout = 10
	for {
		if xm.connectorLoopNum != num {
			return
		}
		tc := &tls.Config{
			ServerName:         strings.Split(xm.jid, "@")[1],
			InsecureSkipVerify: true,
		}
		options := gxmpp.Options{
			Host: xm.server,
			User: xm.jid,
			Password: xm.password,
			NoTLS: true,
			StartTLS: xm.ssl,
			Session: true,
			TLSConfig: tc,
		}
		var err error
		xm.conn, err = options.NewClient()
		if err != nil {
			xm.connected = false
			fmt.Printf("XMPP failed to connect / disconnected: %s\n", err)
			fmt.Printf("Retrying in %ds\n", xm.timeout)
			time.Sleep(time.Duration(xm.timeout) * time.Second)
			xm.timeout *= 2
			if xm.timeout > 600 {
				xm.timeout = 600
			}
		} else {
			xm.connected = true
			xm.timeout = 10
			err = xm.handleXMPP()
			if err != nil {
				xm.connected = false
				fmt.Printf("XMPP disconnected: %s\n", err)
				fmt.Printf("Reconnecting.\n")
			}
		}
	}
}

func (xm *XMPP) xmppKeepAlive() chan bool {
	done := make(chan bool)
	go func() {
		ticker := time.NewTicker(90 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				if err := xm.conn.PingC2S("", ""); err != nil {
					log.Printf("PING failed %#v\n", err)
				}
			case <-done:
				return
			}
		}
	}()
	return done
}

func (xm *XMPP) handleXMPP() error {
	done := xm.xmppKeepAlive()
	defer close(done)

	for {
		m, err := xm.conn.Recv()
		if err != nil {
			return err
		}

		fmt.Printf("XMPP: %#v\n", m)

		switch v := m.(type) {
		case gxmpp.Chat:
			log.Printf("== Receiving %#v\n", v)

			if v.Text == "" && v.Type == "groupchat" && !strings.Contains(v.Remote, "/") {
				// Empty message when we joined group chat
				xm.handler.Joined(RoomID(v.Remote))
				if v.Subject != "" {
					xm.handler.RoomInfoUpdated(RoomID(v.Remote), &RoomInfo{
						Description: v.Subject,
					})
				}
				continue
			}

			if v.Text == "" || v.Remote == xm.jid {
				continue
			}

			event := &Event{
				Type: EVENT_MESSAGE,
				Text: v.Text,
			}
			log.Printf("Remote: %s\n", v.Remote)

			if strings.HasPrefix(event.Text, "/me ") {
				event.Type = EVENT_ACTION
				event.Text = strings.Replace(event.Text, "/me ", "", 1)
			}

			if v.Type == "chat" {
				remote_jid := strings.Split(v.Remote, "/")[0]
				event.Author = UserID(remote_jid)
				xm.handler.Event(event)
			}
			if v.Type == "groupchat" {
				remote := strings.Split(v.Remote, "/")
				if len(remote) != 2 {
					log.Printf("Invalid remote: %s\n", v.Remote)
					continue
				}
				event.Room = RoomID(remote[0])
				event.Author = UserID(remote[1] + "@" + remote[0])

				if strings.Contains(v.Text, "has set the subject to:") {
					// TODO
					continue
				}

				xm.handler.Event(event)
			}
		case gxmpp.Presence:
			remote := strings.Split(v.From, "/")
			if muc, ok := xm.isMUC[remote[0]]; ok && muc && len(remote) == 2 {
				event := &Event{
					Type: EVENT_JOIN,
					Room: RoomID(remote[0]),
					Author: UserID(remote[1] + "@" + remote[0]),
				}
				if v.Type == "unavailable" {
					event.Type = EVENT_LEAVE
				}
				xm.handler.Event(event)
			}
			// Do nothing.
		}
	}
}

func (xm *XMPP) User() UserID {
	return UserID(xm.jid)
}

func (xm *XMPP) SetUserInfo(info *UserInfo) error {
	//TODO
	return fmt.Errorf("Not implemented")
}

func (xm *XMPP) SetRoomInfo(roomId RoomID, info *RoomInfo) error {
	// TODO
	return fmt.Errorf("Not implemented")
}

func (xm *XMPP) Join(roomId RoomID) error {
	xm.isMUC[string(roomId)] = true

	fmt.Printf("Join %s with nick %s\n", roomId, xm.nickname)
	_, err := xm.conn.JoinMUCNoHistory(string(roomId), xm.nickname)
	return err
}

func (xm *XMPP) Invite(userId UserID, roomId RoomID) error {
	// TODO
	return fmt.Errorf("Not implemented")
}

func (xm *XMPP) Leave(roomId RoomID) {
	// TODO
}

func (xm *XMPP) Send(event *Event) error {
	if len(event.Recipient) > 0 {
		xm.conn.Send(gxmpp.Chat{
			Type: "chat",
			Remote: string(event.Recipient),
			Text: event.Text,
		})
		return nil
	} else if len(event.Room) > 0 {
		xm.conn.Send(gxmpp.Chat{
			Type: "groupchat",
			Remote: string(event.Room),
			Text: event.Text,
		})
		return nil
	} else {
		return fmt.Errorf("Invalid event")
	}
}

func (xm *XMPP) Close() {
	xm.conn.Close()
	xm.conn = nil
	xm.connectorLoopNum += 1
}