You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
11 KiB

8 years ago
8 years ago
  1. package clients
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "sync"
  8. "github.com/matrix-org/go-neb/api"
  9. "github.com/matrix-org/go-neb/database"
  10. "github.com/matrix-org/go-neb/matrix"
  11. "github.com/matrix-org/go-neb/metrics"
  12. "github.com/matrix-org/go-neb/types"
  13. shellwords "github.com/mattn/go-shellwords"
  14. log "github.com/sirupsen/logrus"
  15. "maunium.net/go/mautrix"
  16. mevt "maunium.net/go/mautrix/event"
  17. "maunium.net/go/mautrix/id"
  18. )
  19. // A Clients is a collection of clients used for bot services.
  20. type Clients struct {
  21. db database.Storer
  22. httpClient *http.Client
  23. dbMutex sync.Mutex
  24. mapMutex sync.Mutex
  25. clients map[id.UserID]BotClient
  26. }
  27. // New makes a new collection of matrix clients
  28. func New(db database.Storer, cli *http.Client) *Clients {
  29. clients := &Clients{
  30. db: db,
  31. httpClient: cli,
  32. clients: make(map[id.UserID]BotClient), // user_id => BotClient
  33. }
  34. return clients
  35. }
  36. // Client gets a client for the userID
  37. func (c *Clients) Client(userID id.UserID) (*BotClient, error) {
  38. entry := c.getClient(userID)
  39. if entry.Client != nil {
  40. return &entry, nil
  41. }
  42. entry, err := c.loadClientFromDB(userID)
  43. return &entry, err
  44. }
  45. // Update updates the config for a matrix client
  46. func (c *Clients) Update(config api.ClientConfig) (api.ClientConfig, error) {
  47. _, old, err := c.updateClientInDB(config)
  48. return old.config, err
  49. }
  50. // Start listening on client /sync streams
  51. func (c *Clients) Start() error {
  52. configs, err := c.db.LoadMatrixClientConfigs()
  53. if err != nil {
  54. return err
  55. }
  56. for _, cfg := range configs {
  57. if cfg.Sync {
  58. if _, err := c.Client(cfg.UserID); err != nil {
  59. return err
  60. }
  61. }
  62. }
  63. return nil
  64. }
  65. func (c *Clients) getClient(userID id.UserID) BotClient {
  66. c.mapMutex.Lock()
  67. defer c.mapMutex.Unlock()
  68. return c.clients[userID]
  69. }
  70. func (c *Clients) setClient(client BotClient) {
  71. c.mapMutex.Lock()
  72. defer c.mapMutex.Unlock()
  73. c.clients[client.config.UserID] = client
  74. }
  75. func (c *Clients) loadClientFromDB(userID id.UserID) (entry BotClient, err error) {
  76. c.dbMutex.Lock()
  77. defer c.dbMutex.Unlock()
  78. entry = c.getClient(userID)
  79. if entry.Client != nil {
  80. return
  81. }
  82. if entry.config, err = c.db.LoadMatrixClientConfig(userID); err != nil {
  83. if err == sql.ErrNoRows {
  84. err = fmt.Errorf("client with user ID %s does not exist", userID)
  85. }
  86. return
  87. }
  88. if err = c.initClient(&entry); err != nil {
  89. return
  90. }
  91. c.setClient(entry)
  92. return
  93. }
  94. func (c *Clients) updateClientInDB(newConfig api.ClientConfig) (new, old BotClient, err error) {
  95. c.dbMutex.Lock()
  96. defer c.dbMutex.Unlock()
  97. old = c.getClient(newConfig.UserID)
  98. if old.Client != nil && old.config == newConfig {
  99. // Already have a client with that config.
  100. new = old
  101. return
  102. }
  103. new.config = newConfig
  104. if err = c.initClient(&new); err != nil {
  105. return
  106. }
  107. // set the new display name if they differ
  108. if old.config.DisplayName != new.config.DisplayName {
  109. if err := new.SetDisplayName(new.config.DisplayName); err != nil {
  110. // whine about it but don't stop: this isn't fatal.
  111. log.WithFields(log.Fields{
  112. log.ErrorKey: err,
  113. "displayname": new.config.DisplayName,
  114. "user_id": new.config.UserID,
  115. }).Error("Failed to set display name")
  116. }
  117. }
  118. if old.config, err = c.db.StoreMatrixClientConfig(new.config); err != nil {
  119. new.StopSync()
  120. return
  121. }
  122. if old.Client != nil {
  123. old.Client.StopSync()
  124. return
  125. }
  126. c.setClient(new)
  127. return
  128. }
  129. func (c *Clients) onMessageEvent(botClient *BotClient, event *mevt.Event) {
  130. services, err := c.db.LoadServicesForUser(botClient.UserID)
  131. if err != nil {
  132. log.WithFields(log.Fields{
  133. log.ErrorKey: err,
  134. "room_id": event.RoomID,
  135. "service_user_id": botClient.UserID,
  136. }).Warn("Error loading services")
  137. }
  138. message := event.Content.AsMessage()
  139. body := message.Body
  140. if body == "" {
  141. return
  142. }
  143. // filter m.notice to prevent loops
  144. if message.MsgType == mevt.MsgNotice {
  145. return
  146. }
  147. // replace all smart quotes with their normal counterparts so shellwords can parse it
  148. body = strings.Replace(body, ``, `'`, -1)
  149. body = strings.Replace(body, ``, `'`, -1)
  150. body = strings.Replace(body, ``, `"`, -1)
  151. body = strings.Replace(body, ``, `"`, -1)
  152. var responses []interface{}
  153. for _, service := range services {
  154. if body[0] == '!' { // message is a command
  155. args, err := shellwords.Parse(body[1:])
  156. if err != nil {
  157. args = strings.Split(body[1:], " ")
  158. }
  159. if response := runCommandForService(service.Commands(botClient), event, args); response != nil {
  160. responses = append(responses, response)
  161. }
  162. } else { // message isn't a command, it might need expanding
  163. expansions := runExpansionsForService(service.Expansions(botClient), event, body)
  164. responses = append(responses, expansions...)
  165. }
  166. }
  167. for _, content := range responses {
  168. if _, err := botClient.SendMessageEvent(event.RoomID, mevt.EventMessage, content); err != nil {
  169. log.WithFields(log.Fields{
  170. "room_id": event.RoomID,
  171. "content": content,
  172. "sender": event.Sender,
  173. }).WithError(err).Error("Failed to send command response")
  174. }
  175. }
  176. }
  177. // runCommandForService runs a single command read from a matrix event. Runs
  178. // the matching command with the longest path. Returns the JSON encodable
  179. // content of a single matrix message event to use as a response or nil if no
  180. // response is appropriate.
  181. func runCommandForService(cmds []types.Command, event *mevt.Event, arguments []string) interface{} {
  182. var bestMatch *types.Command
  183. for i, command := range cmds {
  184. matches := command.Matches(arguments)
  185. betterMatch := bestMatch == nil || len(bestMatch.Path) < len(command.Path)
  186. if matches && betterMatch {
  187. bestMatch = &cmds[i]
  188. }
  189. }
  190. if bestMatch == nil {
  191. return nil
  192. }
  193. cmdArgs := arguments[len(bestMatch.Path):]
  194. log.WithFields(log.Fields{
  195. "room_id": event.RoomID,
  196. "user_id": event.Sender,
  197. "command": bestMatch.Path,
  198. }).Info("Executing command")
  199. content, err := bestMatch.Command(event.RoomID, event.Sender, cmdArgs)
  200. if err != nil {
  201. if content != nil {
  202. log.WithFields(log.Fields{
  203. log.ErrorKey: err,
  204. "room_id": event.RoomID,
  205. "user_id": event.Sender,
  206. "command": bestMatch.Path,
  207. "args": cmdArgs,
  208. }).Warn("Command returned both error and content.")
  209. }
  210. metrics.IncrementCommand(bestMatch.Path[0], metrics.StatusFailure)
  211. content = mevt.MessageEventContent{
  212. MsgType: mevt.MsgNotice,
  213. Body: err.Error(),
  214. }
  215. } else {
  216. metrics.IncrementCommand(bestMatch.Path[0], metrics.StatusSuccess)
  217. }
  218. return content
  219. }
  220. // run the expansions for a matrix event.
  221. func runExpansionsForService(expans []types.Expansion, event *mevt.Event, body string) []interface{} {
  222. var responses []interface{}
  223. for _, expansion := range expans {
  224. matches := map[string]bool{}
  225. for _, matchingGroups := range expansion.Regexp.FindAllStringSubmatch(body, -1) {
  226. matchingText := matchingGroups[0] // first element is always the complete match
  227. if matches[matchingText] {
  228. // Only expand the first occurance of a matching string
  229. continue
  230. }
  231. matches[matchingText] = true
  232. if response := expansion.Expand(event.RoomID, event.Sender, matchingGroups); response != nil {
  233. responses = append(responses, response)
  234. }
  235. }
  236. }
  237. return responses
  238. }
  239. func (c *Clients) onBotOptionsEvent(client *mautrix.Client, event *mevt.Event) {
  240. // see if these options are for us. The state key is the user ID with a leading _
  241. // to get around restrictions in the HS about having user IDs as state keys.
  242. if event.StateKey == nil {
  243. return
  244. }
  245. targetUserID := id.UserID(strings.TrimPrefix(*event.StateKey, "_"))
  246. if targetUserID != client.UserID {
  247. return
  248. }
  249. // these options fully clobber what was there previously.
  250. opts := types.BotOptions{
  251. UserID: client.UserID,
  252. RoomID: event.RoomID,
  253. SetByUserID: event.Sender,
  254. Options: event.Content.Raw,
  255. }
  256. if _, err := c.db.StoreBotOptions(opts); err != nil {
  257. log.WithFields(log.Fields{
  258. log.ErrorKey: err,
  259. "room_id": event.RoomID,
  260. "bot_user_id": client.UserID,
  261. "set_by_user_id": event.Sender,
  262. }).Error("Failed to persist bot options")
  263. }
  264. }
  265. func (c *Clients) onRoomMemberEvent(client *mautrix.Client, event *mevt.Event) {
  266. if event.StateKey == nil || *event.StateKey != client.UserID.String() {
  267. return // not our member event
  268. }
  269. membership := event.Content.AsMember().Membership
  270. if membership == "invite" {
  271. logger := log.WithFields(log.Fields{
  272. "room_id": event.RoomID,
  273. "service_user_id": client.UserID,
  274. "inviter": event.Sender,
  275. })
  276. logger.Print("Accepting invite from user")
  277. content := struct {
  278. Inviter id.UserID `json:"inviter"`
  279. }{event.Sender}
  280. if _, err := client.JoinRoom(event.RoomID.String(), "", content); err != nil {
  281. logger.WithError(err).Print("Failed to join room")
  282. } else {
  283. logger.Print("Joined room")
  284. }
  285. }
  286. }
  287. func (c *Clients) initClient(botClient *BotClient) error {
  288. config := botClient.config
  289. client, err := mautrix.NewClient(config.HomeserverURL, config.UserID, config.AccessToken)
  290. if err != nil {
  291. return err
  292. }
  293. client.Client = c.httpClient
  294. client.DeviceID = config.DeviceID
  295. if client.DeviceID == "" {
  296. log.Warn("Device ID is not set which will result in E2E encryption/decryption not working")
  297. }
  298. botClient.Client = client
  299. syncer := client.Syncer.(*mautrix.DefaultSyncer)
  300. nebStore := &matrix.NEBStore{
  301. InMemoryStore: *mautrix.NewInMemoryStore(),
  302. Database: c.db,
  303. ClientConfig: config,
  304. }
  305. client.Store = nebStore
  306. // TODO: Check that the access token is valid for the userID by peforming
  307. // a request against the server.
  308. if err = botClient.InitOlmMachine(client, nebStore); err != nil {
  309. return err
  310. }
  311. // Register sync callback for maintaining the state store and Olm machine state
  312. botClient.Register(syncer)
  313. syncer.OnEventType(mevt.EventMessage, func(_ mautrix.EventSource, event *mevt.Event) {
  314. c.onMessageEvent(botClient, event)
  315. })
  316. syncer.OnEventType(mevt.Type{Type: "m.room.bot.options", Class: mevt.UnknownEventType}, func(_ mautrix.EventSource, event *mevt.Event) {
  317. c.onBotOptionsEvent(botClient.Client, event)
  318. })
  319. if config.AutoJoinRooms {
  320. syncer.OnEventType(mevt.StateMember, func(_ mautrix.EventSource, event *mevt.Event) {
  321. c.onRoomMemberEvent(client, event)
  322. })
  323. }
  324. // When receiving an encrypted event, attempt to decrypt it using the BotClient's capabilities.
  325. // If successfully decrypted propagate the decrypted event to the clients.
  326. syncer.OnEventType(mevt.EventEncrypted, func(source mautrix.EventSource, evt *mevt.Event) {
  327. encContent := evt.Content.AsEncrypted()
  328. decrypted, err := botClient.DecryptMegolmEvent(evt)
  329. if err != nil {
  330. log.WithFields(log.Fields{
  331. "user_id": config.UserID,
  332. "device_id": encContent.DeviceID,
  333. "session_id": encContent.SessionID,
  334. "sender_key": encContent.SenderKey,
  335. }).WithError(err).Error("Failed to decrypt message")
  336. } else {
  337. if decrypted.Type == mevt.EventMessage {
  338. c.onMessageEvent(botClient, decrypted)
  339. }
  340. log.WithFields(log.Fields{
  341. "type": evt.Type,
  342. "sender": evt.Sender,
  343. "room_id": evt.RoomID,
  344. "state_key": evt.StateKey,
  345. }).Trace("Decrypted event successfully")
  346. }
  347. })
  348. // Ignore events before neb's join event.
  349. eventIgnorer := mautrix.OldEventIgnorer{UserID: config.UserID}
  350. eventIgnorer.Register(syncer)
  351. log.WithFields(log.Fields{
  352. "user_id": config.UserID,
  353. "device_id": config.DeviceID,
  354. "sync": config.Sync,
  355. "auto_join_rooms": config.AutoJoinRooms,
  356. "since": nebStore.LoadNextBatch(config.UserID),
  357. }).Info("Created new client")
  358. if config.Sync {
  359. go botClient.Sync()
  360. }
  361. return nil
  362. }