aboutsummaryrefslogtreecommitdiff
path: root/connector/irc/irc.go
blob: 1327eaad31413e548f2777b3ab6fea97f25b67ca (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package irc

import (
	"fmt"
	_ "os"
	"strings"
	"time"

	"github.com/lrstanley/girc"

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

// User id format: nickname@server

// Room id format: #room_name@server

type IRC struct {
	handler Handler

	connected bool
	timeout   int

	nick   string
	name   string
	server string
	conn   *girc.Client

	joinedRooms map[string]bool
}

func (irc *IRC) SetHandler(h Handler) {
	irc.handler = h
}

func (irc *IRC) Protocol() string {
	return IRC_PROTOCOL
}

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

	var err error

	irc.nick, err = c.GetString("nick")
	if err != nil {
		return err
	}

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

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

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

	server_pass, _ := c.GetString("server_pass", "")
	sasl_user, _ := c.GetString("sasl_user", "")
	sasl_pass, _ := c.GetString("sasl_pass", "")

	var sasl girc.SASLMech
	if sasl_user != "" && sasl_pass != "" {
		sasl = &girc.SASLPlain{
			User: sasl_user,
			Pass: sasl_pass,
		}
	}

	client := girc.New(girc.Config{
		Server:     irc.server,
		ServerPass: server_pass,
		Port:       port,
		Nick:       irc.nick,
		User:       irc.nick,
		SASL:       sasl,
		//Out: os.Stderr,
		SSL: ssl,
	})

	client.Handlers.Add(girc.CONNECTED, irc.ircConnected)
	//client.Handlers.Add(girc.DISCONNECTED, irc.ircDisconnected)
	//client.Handlers.Add(girc.NICK, irc.ircNick)
	client.Handlers.Add(girc.PRIVMSG, irc.ircPrivmsg)
	client.Handlers.Add(girc.JOIN, irc.ircJoin)
	client.Handlers.Add(girc.PART, irc.ircPart)
	client.Handlers.Add(girc.RPL_NAMREPLY, irc.ircNamreply)
	client.Handlers.Add(girc.TOPIC, irc.ircTopic)
	client.Handlers.Add(girc.RPL_TOPIC, irc.ircRplTopic)

	irc.joinedRooms = make(map[string]bool)

	irc.conn = client
	go irc.connectLoop(client)

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

func (irc *IRC) User() UserID {
	return UserID(irc.nick + "@" + irc.server)
}

func (irc *IRC) checkRoomId(id RoomID) (string, error) {
	x := strings.Split(string(id), "@")
	if len(x) == 1 {
		return "", fmt.Errorf("Please write whole room ID with server: %s@%s", id, irc.server)
	}
	if x[0][0] != '#' || len(x) != 2 || x[1] != irc.server {
		return "", fmt.Errorf("Invalid room ID: %s", id)
	}
	return x[0], nil
}

func (irc *IRC) checkUserId(id UserID) (string, error) {
	x := strings.Split(string(id), "@")
	if len(x) == 1 {
		return "", fmt.Errorf("Please write whole user ID with server: %s@%s", id, irc.server)
	}
	if x[0][0] == '#' || len(x) != 2 || x[1] != irc.server {
		return "", fmt.Errorf("Invalid user ID: %s", id)
	}
	return x[0], nil
}

func (irc *IRC) SetUserInfo(info *UserInfo) error {
	return fmt.Errorf("Not implemented")
}

func (irc *IRC) SetRoomInfo(roomId RoomID, info *RoomInfo) error {
	if irc.conn == nil {
		return fmt.Errorf("Not connected")
	}

	ch, err := irc.checkRoomId(roomId)
	if err != nil {
		return err
	}

	if info.Topic != "" {
		irc.conn.Cmd.Topic(ch, info.Topic)
	}
	if info.Name != "" && info.Name != ch {
		return fmt.Errorf("May not change IRC room name to other than %s", ch)
	}
	if info.Picture.MediaObject != nil {
		return fmt.Errorf("Room picture not supported on IRC")
	}
	return nil
}

func (irc *IRC) Join(roomId RoomID) error {
	if irc.conn == nil {
		return fmt.Errorf("Not connected")
	}

	ch, err := irc.checkRoomId(roomId)
	if err != nil {
		return err
	}

	irc.conn.Cmd.Join(ch)
	return nil
}

func (irc *IRC) Invite(userId UserID, roomId RoomID) error {
	if irc.conn == nil {
		return fmt.Errorf("Not connected")
	}

	who, err := irc.checkUserId(userId)
	if err != nil {
		return err
	}

	if roomId == "" {
		return nil
	}

	ch, err := irc.checkRoomId(roomId)
	if err != nil {
		return err
	}

	irc.conn.Cmd.Invite(ch, who)
	return nil
}

func (irc *IRC) Leave(roomId RoomID) {
	if irc.conn == nil {
		return
	}

	ch, err := irc.checkRoomId(roomId)
	if err != nil {
		return
	}

	irc.conn.Cmd.Part(ch)
}

func (irc *IRC) SearchForUsers(query string) ([]UserSearchResult, error) {
	// TODO
	return nil, fmt.Errorf("Not implemented")
}

func (irc *IRC) Send(event *Event) (string, error) {
	if irc.conn == nil {
		return "", fmt.Errorf("Not connected")
	}

	// Workaround girc bug
	if event.Text[0] == ':' {
		event.Text = " " + event.Text
	}

	dest := ""
	if event.Room != "" {
		ch, err := irc.checkRoomId(event.Room)
		if err != nil {
			return "", err
		}
		dest = ch
	} else if event.Recipient != "" {
		ui, err := irc.checkUserId(event.Recipient)
		if err != nil {
			return "", err
		}
		dest = ui
	} else {
		return "", fmt.Errorf("Invalid target")
	}

	if event.Attachments != nil && len(event.Attachments) > 0 {
		for _, at := range event.Attachments {
			url := at.URL()
			if url == "" {
				// TODO find a way to send them using some hosing of some kind
				return "", fmt.Errorf("Attachment without URL sent to IRC")
			} else {
				irc.conn.Cmd.Message(dest, fmt.Sprintf("%s (%s, %dkb)",
					url, at.Mimetype(), at.Size()/1024))
			}
		}
	}

	if event.Type == EVENT_MESSAGE {
		irc.conn.Cmd.Message(dest, event.Text)
	} else if event.Type == EVENT_ACTION {
		irc.conn.Cmd.Action(dest, event.Text)
	} else {
		return "", fmt.Errorf("Invalid event type")
	}
	return "", nil
}

func (irc *IRC) UserCommand(cm string) {
	irc.handler.SystemMessage("Command not supported.")
}

func (irc *IRC) Close() {
	conn := irc.conn
	irc.conn = nil
	irc.connected = false
	if conn != nil {
		conn.Close()
	}
}

func (irc *IRC) connectLoop(c *girc.Client) {
	irc.timeout = 10
	for {
		if irc.conn != c {
			return
		}
		if err := c.Connect(); err != nil {
			irc.connected = false
			irc.handler.SystemMessage(fmt.Sprintf("IRC failed to connect / disconnected (%s), reconnecting in %ds", err, irc.timeout))
			time.Sleep(time.Duration(irc.timeout) * time.Second)
			irc.timeout *= 2
			if irc.timeout > 600 {
				irc.timeout = 600
			}
		} else {
			return
		}
	}
}

func (irc *IRC) ircConnected(c *girc.Client, e girc.Event) {
	irc.handler.SystemMessage("Connected to IRC.")
	irc.timeout = 10
	irc.connected = true

	for room, joined := range irc.joinedRooms {
		if joined {
			irc.conn.Cmd.Join(room)
		}
	}
}

func (irc *IRC) ircPrivmsg(c *girc.Client, e girc.Event) {
	ev := &Event{
		Type:   EVENT_MESSAGE,
		Author: UserID(e.Source.Name + "@" + irc.server),
		Text:   e.Last(),
	}
	if e.IsFromChannel() {
		ev.Room = RoomID(e.Params[0] + "@" + irc.server)
	}
	if e.IsAction() {
		ev.Type = EVENT_ACTION
	}
	irc.handler.Event(ev)
}

func (irc *IRC) ircJoin(c *girc.Client, e girc.Event) {
	room := RoomID(e.Params[0] + "@" + irc.server)
	if e.Source.Name == irc.nick {
		irc.handler.Joined(room)
		irc.joinedRooms[e.Params[0]] = true
	} else {
		user := UserID(e.Source.Name + "@" + irc.server)
		ev := &Event{
			Type:   EVENT_JOIN,
			Author: user,
			Room:   room,
		}
		irc.handler.Event(ev)
		irc.handler.UserInfoUpdated(user, &UserInfo{
			DisplayName: e.Source.Name,
		})
	}
}

func (irc *IRC) ircPart(c *girc.Client, e girc.Event) {
	room := RoomID(e.Params[0] + "@" + irc.server)
	if e.Source.Name == irc.nick {
		irc.handler.Left(room)
		delete(irc.joinedRooms, e.Params[0])
	} else {
		user := UserID(e.Source.Name + "@" + irc.server)
		ev := &Event{
			Type:   EVENT_LEAVE,
			Author: user,
			Room:   room,
		}
		irc.handler.Event(ev)
		irc.handler.UserInfoUpdated(user, &UserInfo{
			DisplayName: e.Source.Name,
		})
	}
}

func (irc *IRC) ircNamreply(c *girc.Client, e girc.Event) {
	room := RoomID(e.Params[2] + "@" + irc.server)
	names := strings.Split(e.Last(), " ")
	for _, name := range names {
		if name[0] == '@' {
			name = name[1:]
		}
		src := girc.ParseSource(name)
		if src.Name != irc.nick {
			irc.handler.Event(&Event{
				Type:   EVENT_JOIN,
				Author: UserID(src.Name + "@" + irc.server),
				Room:   room,
			})
		}
	}
}

func (irc *IRC) ircTopic(c *girc.Client, e girc.Event) {
	source := UserID(e.Source.Name + "@" + irc.server)
	room := RoomID(e.Params[0] + "@" + irc.server)
	topic := e.Last()
	irc.handler.RoomInfoUpdated(room, source, &RoomInfo{
		Topic: topic,
	})
}

func (irc *IRC) ircRplTopic(c *girc.Client, e girc.Event) {
	room := RoomID(e.Params[1] + "@" + irc.server)
	topic := e.Last()
	irc.handler.RoomInfoUpdated(room, "", &RoomInfo{
		Topic: topic,
	})
}