aboutsummaryrefslogtreecommitdiff
path: root/matrix/matrix.go
blob: a2e3767646f927a97219a58a6f06c59f86b80345 (plain)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// gomuks - A terminal Matrix client written in Go.
// Copyright (C) 2018 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package matrix

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"gopkg.in/russross/blackfriday.v2"
	"maunium.net/go/gomatrix"
	"maunium.net/go/gomuks/config"
	"maunium.net/go/gomuks/debug"
	"maunium.net/go/gomuks/interface"
	"maunium.net/go/gomuks/matrix/pushrules"
	"maunium.net/go/gomuks/matrix/rooms"
)

// Container is a wrapper for a gomatrix Client and some other stuff.
//
// It is used for all Matrix calls from the UI and Matrix event handlers.
type Container struct {
	client  *gomatrix.Client
	syncer  *GomuksSyncer
	gmx     ifc.Gomuks
	ui      ifc.GomuksUI
	config  *config.Config
	running bool
	stop    chan bool

	typing int64
}

// NewContainer creates a new Container for the given Gomuks instance.
func NewContainer(gmx ifc.Gomuks) *Container {
	c := &Container{
		config: gmx.Config(),
		ui:     gmx.UI(),
		gmx:    gmx,
	}

	return c
}

// InitClient initializes the gomatrix client and connects to the homeserver specified in the config.
func (c *Container) InitClient() error {
	if len(c.config.HS) == 0 {
		return fmt.Errorf("no homeserver in config")
	}

	if c.client != nil {
		c.Stop()
		c.client = nil
	}

	var mxid, accessToken string
	if c.config.Session != nil {
		accessToken = c.config.Session.AccessToken
		mxid = c.config.UserID
	}

	var err error
	c.client, err = gomatrix.NewClient(c.config.HS, mxid, accessToken)
	if err != nil {
		return err
	}

	c.stop = make(chan bool, 1)

	if c.config.Session != nil && len(accessToken) > 0 {
		go c.Start()
	}
	return nil
}

// Initialized returns whether or not the gomatrix client is initialized (see InitClient())
func (c *Container) Initialized() bool {
	return c.client != nil
}

// Login sends a password login request with the given username and password.
func (c *Container) Login(user, password string) error {
	resp, err := c.client.Login(&gomatrix.ReqLogin{
		Type:                     "m.login.password",
		User:                     user,
		Password:                 password,
		InitialDeviceDisplayName: "gomuks",
	})
	if err != nil {
		return err
	}
	c.client.SetCredentials(resp.UserID, resp.AccessToken)
	c.config.UserID = resp.UserID
	c.config.Save()

	c.config.Session = c.config.NewSession(resp.UserID)
	c.config.Session.AccessToken = resp.AccessToken
	c.config.Session.Save()

	go c.Start()

	return nil
}

// Stop stops the Matrix syncer.
func (c *Container) Stop() {
	if c.running {
		c.stop <- true
		c.client.StopSync()
	}
}

// Client returns the underlying gomatrix client object.
func (c *Container) Client() *gomatrix.Client {
	return c.client
}

// UpdatePushRules fetches the push notification rules from the server and stores them in the current Session object.
func (c *Container) UpdatePushRules() {
	debug.Print("Updating push rules...")
	resp, err := pushrules.GetPushRules(c.client)
	if err != nil {
		debug.Print("Failed to fetch push rules:", err)
	}
	c.config.Session.PushRules = resp
}

// PushRules returns the push notification rules. If no push rules are cached, UpdatePushRules() will be called first.
func (c *Container) PushRules() *pushrules.PushRuleset {
	if c.config.Session.PushRules == nil {
		c.UpdatePushRules()
	}
	return c.config.Session.PushRules
}

// UpdateRoomList fetches the list of rooms the user has joined and sends them to the UI.
func (c *Container) UpdateRoomList() {
	resp, err := c.client.JoinedRooms()
	if err != nil {
		respErr, _ := err.(gomatrix.HTTPError).WrappedError.(gomatrix.RespError)
		if respErr.ErrCode == "M_UNKNOWN_TOKEN" {
			c.OnLogout()
			return
		}
		debug.Print("Error fetching room list:", err)
		return
	}

	c.ui.MainView().SetRooms(resp.JoinedRooms)
}

// OnLogout stops the syncer and moves the UI back to the login view.
func (c *Container) OnLogout() {
	c.Stop()
	c.ui.SetView(ifc.ViewLogin)
}

// OnLogin initializes the syncer and updates the room list.
func (c *Container) OnLogin() {
	c.client.Store = c.config.Session

	c.syncer = NewGomuksSyncer(c.config.Session)
	c.syncer.OnEventType("m.room.message", c.HandleMessage)
	c.syncer.OnEventType("m.room.member", c.HandleMembership)
	c.syncer.OnEventType("m.typing", c.HandleTyping)
	c.syncer.OnEventType("m.push_rules", c.HandlePushRules)
	c.syncer.OnEventType("m.tag", c.HandleTag)
	c.client.Syncer = c.syncer

	c.UpdateRoomList()
}

// Start moves the UI to the main view, calls OnLogin() and runs the syncer forever until stopped with Stop()
func (c *Container) Start() {
	defer c.gmx.Recover()

	c.ui.SetView(ifc.ViewMain)
	c.OnLogin()

	if c.client == nil {
		return
	}

	debug.Print("Starting sync...")
	c.running = true
	for {
		select {
		case <-c.stop:
			debug.Print("Stopping sync...")
			c.running = false
			return
		default:
			if err := c.client.Sync(); err != nil {
				debug.Print("Sync() errored", err)
			} else {
				debug.Print("Sync() returned without error")
			}
		}
	}
}

// HandleMessage is the event handler for the m.room.message timeline event.
func (c *Container) HandleMessage(evt *gomatrix.Event) {
	mainView := c.ui.MainView()
	roomView := mainView.GetRoom(evt.RoomID)
	if roomView == nil {
		return
	}

	message := mainView.ParseEvent(roomView, evt)
	if message != nil {
		if c.syncer.FirstSyncDone {
			pushRules := c.PushRules().GetActions(roomView.MxRoom(), evt).Should()
			mainView.NotifyMessage(roomView.MxRoom(), message, pushRules)
		}
		roomView.AddMessage(message, ifc.AppendMessage)
		c.ui.Render()
	}
}

// HandlePushRules is the event handler for the m.push_rules account data event.
func (c *Container) HandlePushRules(evt *gomatrix.Event) {
	debug.Print("Received updated push rules")
	var err error
	c.config.Session.PushRules, err = pushrules.EventToPushRules(evt)
	if err != nil {
		debug.Print("Failed to convert event to push rules:", err)
	}
}

// HandleTag is the event handler for the m.tag account data event.
func (c *Container) HandleTag(evt *gomatrix.Event) {
	debug.Print("Received updated tags")
	dat, _ := json.MarshalIndent(&evt.Content, "", "  ")
	debug.Print(string(dat))
}

func (c *Container) processOwnMembershipChange(evt *gomatrix.Event) {
	membership, _ := evt.Content["membership"].(string)
	prevMembership := "leave"
	if evt.Unsigned.PrevContent != nil {
		prevMembership, _ = evt.Unsigned.PrevContent["membership"].(string)
	}
	if membership == prevMembership {
		return
	}
	switch membership {
	case "join":
		c.ui.MainView().AddRoom(evt.RoomID)
	case "leave":
		c.ui.MainView().RemoveRoom(evt.RoomID)
	}
}

// HandleMembership is the event handler for the m.room.membership state event.
func (c *Container) HandleMembership(evt *gomatrix.Event) {
	if evt.StateKey != nil && *evt.StateKey == c.config.Session.UserID {
		c.processOwnMembershipChange(evt)
	}

	mainView := c.ui.MainView()
	roomView := mainView.GetRoom(evt.RoomID)
	if roomView == nil {
		return
	}

	message := mainView.ParseEvent(roomView, evt)
	if message != nil {
		// TODO this shouldn't be necessary
		roomView.MxRoom().UpdateState(evt)
		// TODO This should probably also be in a different place
		roomView.UpdateUserList()

		if c.syncer.FirstSyncDone {
			pushRules := c.PushRules().GetActions(roomView.MxRoom(), evt).Should()
			mainView.NotifyMessage(roomView.MxRoom(), message, pushRules)
		}
		roomView.AddMessage(message, ifc.AppendMessage)
		c.ui.Render()
	}
}

// HandleTyping is the event handler for the m.typing event.
func (c *Container) HandleTyping(evt *gomatrix.Event) {
	users := evt.Content["user_ids"].([]interface{})

	strUsers := make([]string, len(users))
	for i, user := range users {
		strUsers[i] = user.(string)
	}
	c.ui.MainView().SetTyping(evt.RoomID, strUsers)
}

// SendMessage sends a message with the given text to the given room.
func (c *Container) SendMessage(roomID, msgtype, text string) (string, error) {
	defer c.gmx.Recover()
	c.SendTyping(roomID, false)
	resp, err := c.client.SendMessageEvent(roomID, "m.room.message",
		gomatrix.TextMessage{MsgType: msgtype, Body: text})
	if err != nil {
		return "", err
	}
	return resp.EventID, nil
}

func (c *Container) SendMarkdownMessage(roomID, msgtype, text string) (string, error) {
	defer c.gmx.Recover()

	html := string(blackfriday.Run([]byte(text)))
	if html == text {
		return c.SendMessage(roomID, msgtype, text)
	}

	c.SendTyping(roomID, false)
	resp, err := c.client.SendMessageEvent(roomID, "m.room.message",
		map[string]interface{}{
			"msgtype":        msgtype,
			"body":           text,
			"format":         "org.matrix.custom.html",
			"formatted_body": html,
		})
	if err != nil {
		return "", err
	}
	return resp.EventID, nil
}

// SendTyping sets whether or not the user is typing in the given room.
func (c *Container) SendTyping(roomID string, typing bool) {
	defer c.gmx.Recover()
	ts := time.Now().Unix()
	if c.typing > ts && typing {
		return
	}

	if typing {
		c.client.UserTyping(roomID, true, 20000)
		c.typing = ts + 15
	} else {
		c.client.UserTyping(roomID, false, 0)
		c.typing = 0
	}
}

// JoinRoom makes the current user try to join the given room.
func (c *Container) JoinRoom(roomID string) error {
	if len(roomID) == 0 {
		return fmt.Errorf("invalid room ID")
	}

	server := ""
	if roomID[0] == '!' {
		server = roomID[strings.Index(roomID, ":")+1:]
	}

	_, err := c.client.JoinRoom(roomID, server, nil)
	if err != nil {
		return err
	}

	return nil
}

// LeaveRoom makes the current user leave the given room.
func (c *Container) LeaveRoom(roomID string) error {
	if len(roomID) == 0 {
		return fmt.Errorf("invalid room ID")
	}

	_, err := c.client.LeaveRoom(roomID)
	if err != nil {
		return err
	}

	return nil
}

// getState requests the state of the given room.
func (c *Container) getState(roomID string) []*gomatrix.Event {
	content := make([]*gomatrix.Event, 0)
	err := c.client.StateEvent(roomID, "", "", &content)
	if err != nil {
		debug.Print("Error getting state of", roomID, err)
		return nil
	}
	return content
}

// GetHistory fetches room history.
func (c *Container) GetHistory(roomID, prevBatch string, limit int) ([]gomatrix.Event, string, error) {
	resp, err := c.client.Messages(roomID, prevBatch, "", 'b', limit)
	if err != nil {
		return nil, "", err
	}
	return resp.Chunk, resp.End, nil
}

// GetRoom gets the room instance stored in the session.
//
// If the room doesn't have any state events stored, its state will be updated.
func (c *Container) GetRoom(roomID string) *rooms.Room {
	room := c.config.Session.GetRoom(roomID)
	if room != nil && len(room.State) == 0 {
		events := c.getState(room.ID)
		if events != nil {
			for _, event := range events {
				room.UpdateState(event)
			}
		}
	}
	return room
}

var mxcRegex = regexp.MustCompile("mxc://(.+)/(.+)")

func (c *Container) Download(mxcURL string) (data []byte, hs, id string, err error) {
	parts := mxcRegex.FindStringSubmatch(mxcURL)
	if parts == nil || len(parts) != 3 {
		err = fmt.Errorf("invalid matrix content URL")
		return
	}

	hs = parts[1]
	id = parts[2]

	cacheFile := c.GetCachePath(hs, id)
	if _, err = os.Stat(cacheFile); err != nil {
		data, err = ioutil.ReadFile(cacheFile)
		if err == nil {
			return
		}
	}

	data, err = c.download(hs, id, cacheFile)
	return
}

func (c *Container) download(hs, id, cacheFile string) (data []byte, err error) {
	dlURL, _ := url.Parse(c.client.HomeserverURL.String())
	dlURL.Path = path.Join(dlURL.Path, "/_matrix/media/v1/download", hs, id)

	var resp *http.Response
	resp, err = c.client.Client.Get(dlURL.String())
	if err != nil {
		return
	}
	defer resp.Body.Close()

	var buf bytes.Buffer
	_, err = io.Copy(&buf, resp.Body)
	if err != nil {
		return
	}

	data = buf.Bytes()

	err = ioutil.WriteFile(cacheFile, data, 0600)
	return
}

func (c *Container) GetCachePath(homeserver, fileID string) string {
	dir := filepath.Join(c.config.MediaDir, homeserver)

	err := os.MkdirAll(dir, 0700)
	if err != nil {
		return ""
	}

	return filepath.Join(dir, fileID)
}