about summary refs log tree commit diff
path: root/sync.go
blob: b1f5544f46df49e0f7fefa5ebec2a9deb130f07b (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
package matrix

import (
	"encoding/json"
	"fmt"

	"gopkg.in/h2non/gentleman.v2"
	"gopkg.in/h2non/gentleman.v2/plugins/query"
)

// Sync syncs
func Sync(authinfo Authinfo) (RespSync, error) {
	cli := gentleman.New()
	cli.URL(authinfo.HomeServer)

	req := cli.Request()
	req.Path("/_matrix/client/r0/sync")
	req.Method("GET")

	req.Use(query.Set("access_token", authinfo.AccessToken))

	res, err := req.Send()
	if err != nil {
		fmt.Println("ERR1")
		return RespSync{}, err
	}
	if !res.Ok {
		fmt.Println("ERR2")
		fmt.Println(res)
		return RespSync{}, err
	}

	var syncReponse RespSync
	if err := json.Unmarshal(res.Bytes(), &syncReponse); err != nil {
		return RespSync{}, err
	}

	return syncReponse, nil
}

// SyncPartial syncs the state using sync token obtained in a previous request
// as a timestamp
func SyncPartial(authinfo Authinfo, nextBatch string, eventsChannel chan PackagedEvent) (RespSync, error) {
	cli := gentleman.New()
	cli.URL(authinfo.HomeServer)

	req := cli.Request()
	req.Path("/_matrix/client/r0/sync")
	req.Method("GET")

	req.Use(query.Set("access_token", authinfo.AccessToken))
	req.Use(query.Set("since", nextBatch))
	req.Use(query.Set("timeout", "1"))

	res, err := req.Send()
	if err != nil {
		fmt.Println("ERR1")
		return RespSync{}, err
	}
	if !res.Ok {
		fmt.Println("ERR2")
		fmt.Println(res)
		return RespSync{}, err
	}

	// unmarshal the response
	var syncReponse RespSync
	if err := json.Unmarshal(res.Bytes(), &syncReponse); err != nil {
		return RespSync{}, err
	}

	// accept all room invites
	for room := range syncReponse.Rooms.Invite {
		err := join(authinfo, room)
		if err != nil {
			return RespSync{}, fmt.Errorf("could not join room: %s", err)
		}
	}

	// iterate over all new events, insert all new events not from the bot itself into the eventsChannel
	for roomname, room := range syncReponse.Rooms.Join {
		for _, event := range room.Timeline.Events {

			packagedEvent := PackagedEvent{
				RoomName: roomname,
				Event:    event,
			}

			// if the event recieved is not from ourself, insert the event into the eventsChannel
			if event.Sender != authinfo.UserID {
				eventsChannel <- packagedEvent
			}
		}
	}
	return syncReponse, nil
}