xmppjs / hubot-xmpp

XMPP adapter for Hubot
181 stars 103 forks source link

List users in a room and invite users #90

Closed anupdhml closed 8 years ago

anupdhml commented 8 years ago

This adds functionality to invite users to rooms, as well as the ability to list the users in a room.

Borrows the invite code from https://github.com/markstory/hubot-xmpp/pull/72 with tests added.

For the list feature, a custom event receivedUsersForRoom is emitted after the server response is successfully parsed, and scripts can listen to it to get the list of users. Let me know if other approach makes sense (saving the data in hubot brain?).

The xmpp specification leaves it up to the client to discard the invites if the user is already in the room, but clients do not seem to follow it (pidgin and gajim at least). I added the functionality to list the users in a room, so that scripts can use it to check if a user is already in the room, and if they are not, send the invite. Something like:

room = {jid: hubotlab@example.com}
usersToInvite = ['anup', 'mark'] 

robot.adapter.getUsersInRoom room

robot.adapter.once 'receivedUsersForRoom', (roomJID, usersInRoom) ->
  for userName in usersToInvite
    if userName not in usersInRoom
      # On clients that support it, users will get a popup with invitation request
      robot.adapter.sendInvite room, "#{userName}@example.com", 'Inviting to test!'

Not entirely sure what happens when there are concurrent requests for getUsersInRoom(), but right now, we are calling it only once at a time.

The list functionality should also be useful in other cases. There's an open issue regarding this in the hubot repo: https://github.com/github/hubot/issues/742

markstory commented 8 years ago

Not entirely sure what happens when there are concurrent requests for getUsersInRoom(), but right now, we are calling it only once at a time.

It looks like the downstream events/messages would happen multiple times which could result in a user receiving multiple invites.

anupdhml commented 8 years ago

Changed getUsersInRoom() to generate (pseudo) random ids and pass it along the chain of server call and events, so that we can uniquely identify each request in case of concurrent requests.

Also modified the function to accept a callback, to be used after the user data is retrieved. The previous code snippet I posted now becomes:

room = {jid: hubotlab@example.com}
usersToInvite = ['anup', 'mark'] 

robot.adapter.getUsersInRoom room, (usersInRoom) ->
  for userName in usersToInvite
    if userName not in usersInRoom
      # On clients that support it, users will get a popup with invitation request
      robot.adapter.sendInvite room, "#{userName}@example.com", 'Inviting to test!'

This way, users writing scripts need not deal with adapter events, and also, we ensure that there are no memory leaks: completedRequest (earlier receivedUsersForRoom) events have one-time listeners internally.