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
|
package appservice
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"git.deuxfleurs.fr/Deuxfleurs/easybridge/connector"
"git.deuxfleurs.fr/Deuxfleurs/easybridge/mxlib"
)
type Config struct {
HttpBindAddr string
Server string
DbType string
DbPath string
MatrixDomain string
}
var registration *mxlib.Registration
var config *Config
func Start(r *mxlib.Registration, c *Config) (chan error, error) {
registration = r
config = c
err := InitDb()
if err != nil {
return nil, err
}
err = mxRegisterUser(registration.SenderLocalpart)
if mxe, ok := err.(*mxlib.MxError); !ok || mxe.ErrCode != "M_USER_IN_USE" {
return nil, err
}
err = mxProfileDisplayname(ezbrMxId(), "Easybridge")
if err != nil {
return nil, err
}
router := mux.NewRouter()
router.HandleFunc("/_matrix/app/v1/transactions/{txnId}", handleTxn)
router.HandleFunc("/transactions/{txnId}", handleTxn)
errch := make(chan error)
go func() {
log.Printf("Starting HTTP server on %s", config.HttpBindAddr)
err := http.ListenAndServe(config.HttpBindAddr, checkTokenAndLog(router))
if err != nil {
errch <- err
}
}()
return errch, nil
}
func checkTokenAndLog(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if strings.Join(r.Form["access_token"], "") != registration.HsToken {
http.Error(w, "Wrong or no token provided", http.StatusUnauthorized)
return
}
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func handleTxn(w http.ResponseWriter, r *http.Request) {
if r.Method == "PUT" {
var txn mxlib.Transaction
err := json.NewDecoder(r.Body).Decode(&txn)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Warnf("JSON decode error: %s\n", err)
return
}
log.Debugf("Got transaction %#v\n", txn)
for i := range txn.Events {
ev := &txn.Events[i]
if strings.HasPrefix(ev.Sender, "@"+registration.SenderLocalpart) {
// Don't do anything with ezbr events that come back to us
continue
}
err = handleTxnEvent(ev)
if err != nil {
ezbrSystemSend(ev.Sender, fmt.Sprintf("Could not process %s (%s): %s", ev.Type, ev.Sender, err))
}
}
fmt.Fprintf(w, "{}\n")
} else {
http.Error(w, "Expected PUT request", http.StatusBadRequest)
}
}
func handleTxnEvent(e *mxlib.Event) error {
if e.Type == "m.room.message" {
ev := &connector.Event{
Type: connector.EVENT_MESSAGE,
Text: e.Content["body"].(string),
}
typ := e.Content["msgtype"].(string)
if typ == "m.emote" {
ev.Type = connector.EVENT_MESSAGE
}
if pm_room := dbIsPmRoom(e.RoomId); pm_room != nil {
if pm_room.Protocol == EASYBRIDGE_SYSTEM_PROTOCOL {
handleSystemMessage(e.Sender, e.Content["body"].(string))
return nil
}
// If this is a private message room
acct := FindAccount(pm_room.MxUserID, pm_room.AccountName)
if acct == nil {
return fmt.Errorf("Not connected to %s", pm_room.AccountName)
} else if e.Sender == pm_room.MxUserID {
ev.Author = acct.Conn.User()
ev.Recipient = pm_room.UserID
return acct.Conn.Send(ev)
}
} else if room := dbIsPublicRoom(e.RoomId); room != nil {
// If this is a regular room
acct := FindJoinedAccount(e.Sender, room.Protocol, room.RoomID)
if acct != nil {
ev.Author = acct.Conn.User()
ev.Room = room.RoomID
return acct.Conn.Send(ev)
} else {
mxRoomKick(e.RoomId, e.Sender, fmt.Sprintf("Not present in %s on %s, please talk with Easybridge to rejoin", room.RoomID, room.Protocol))
return fmt.Errorf("not joined %s on %s", room.RoomID, room.Protocol)
}
} else {
return fmt.Errorf("Room not bridged")
}
} else if e.Type == "m.room.member" {
ms := e.Content["membership"].(string)
if ms == "leave" {
if pm_room := dbIsPmRoom(e.RoomId); pm_room != nil {
// If leaving a PM room, we must delete it
them_mx := userMxId(pm_room.Protocol, pm_room.UserID)
mxRoomLeaveAs(e.RoomId, them_mx)
db.Delete(pm_room)
return nil
} else if room := dbIsPublicRoom(e.RoomId); room != nil {
// If leaving a public room, leave from server as well
acct := FindJoinedAccount(e.Sender, room.Protocol, room.RoomID)
if acct != nil {
acct.Conn.Leave(room.RoomID)
return nil
// TODO: manage autojoin list, remove this room
} else {
mxRoomKick(e.RoomId, e.Sender, fmt.Sprintf("Not present in %s on %s, please talk with Easybridge to rejoin", room.RoomID, room.Protocol))
return fmt.Errorf("not joined %s on %s", room.RoomID, room.Protocol)
}
} else {
return fmt.Errorf("Room not bridged")
}
}
} else if e.Type == "m.room.topic" {
if room := dbIsPublicRoom(e.RoomId); room != nil {
acct := FindJoinedAccount(e.Sender, room.Protocol, room.RoomID)
if acct != nil {
return acct.Conn.SetRoomInfo(room.RoomID, &connector.RoomInfo{
Topic: e.Content["topic"].(string),
})
} else {
return fmt.Errorf("Could not find room account for %s %s %s", e.Sender, room.Protocol, room.RoomID)
}
}
}
return nil
}
func handleSystemMessage(mxid string, msg string) {
cmd := strings.Fields(msg)
switch cmd[0] {
case "help":
ezbrSystemSend(mxid, "Welcome to Easybridge! Here is a list of available commands:")
ezbrSystemSend(mxid, "- help: request help")
ezbrSystemSend(mxid, "- list: list accounts")
ezbrSystemSend(mxid, "- accounts: list accounts")
ezbrSystemSend(mxid, "- join <protocol or account> <room id>: join public chat room")
ezbrSystemSend(mxid, "- query <protocol or account> <user id>: open private buffer to contact")
case "list", "account", "accounts":
one := false
if accts, ok := registeredAccounts[mxid]; ok {
for name, acct := range accts {
one = true
ezbrSystemSendf(mxid, "- %s (%s)", name, acct.Protocol)
}
}
if !one {
ezbrSystemSendf(mxid, "No account currently configured")
}
case "join":
var account *Account
if accts, ok := registeredAccounts[mxid]; ok {
for name, acct := range accts {
if name == cmd[1] || acct.Protocol == cmd[1] {
account = acct
break
}
}
}
if account != nil {
err := account.Conn.Join(connector.RoomID(cmd[2]))
if err != nil {
ezbrSystemSendf(mxid, "%s", err)
}
} else {
ezbrSystemSendf(mxid, "No account with name or using protocol %s", cmd[1])
}
case "query":
var account *Account
if accts, ok := registeredAccounts[mxid]; ok {
for name, acct := range accts {
if name == cmd[1] || acct.Protocol == cmd[1] {
account = acct
break
}
}
}
if account != nil {
quser := connector.UserID(cmd[2])
err := account.Conn.Invite(quser, connector.RoomID(""))
if err != nil {
ezbrSystemSendf(mxid, "%s", err)
return
}
quser_mxid, err := dbGetMxUser(account.Protocol, quser)
if err != nil {
ezbrSystemSendf(mxid, "%s", err)
return
}
_, err = dbGetMxPmRoom(account.Protocol, quser, quser_mxid, mxid, account.AccountName)
if err != nil {
ezbrSystemSendf(mxid, "%s", err)
}
} else {
ezbrSystemSendf(mxid, "No account with name or using protocol %s", cmd[1])
}
default:
ezbrSystemSend(mxid, "Unrecognized command. Type `help` if you need some help!")
}
}
|