Get online users XMPP4r + Rails

1.5k views Asked by At

I'm trying get online friends by user in XMPP server (Ejabberd). I'm using Ruby on Rails 3.2. The idea is to add in array all online users to use this on view page.

I found asynchronous code (below), but it use Thread and it's difficult to work on controller method.

jid = Jabber::JID.new('user@localhost')

cl = Jabber::Client.new(jid)
cl.connect
cl.auth('123456')
@online_users = [] #online users queue
roster = Jabber::Roster::Helper.new(cl)

mainthread = Thread.current

roster.add_presence_callback { |item,oldpres,pres|
  if item.online?
    @online_users.push item
  else
    @online_users.delete_if {|x| x.jid == item.jid }
  end  
  puts @online_users.inspect
  puts "#{item.jid} - online: #{item.online?}" 
}

cl.send(Jabber::Presence.new.set_show(:dnd))

t = Thread.new { sleep XMPP_REQUEST_TIMEOUT;   mainthread.wakeup;}
Thread.stop

cl.close

So I need some synchronous code, or some way to execute this kind of code in controller method.

Thanks.

2

There are 2 answers

2
Leandro Andrade On BEST ANSWER

For this found another solution that help me:

I installed a mod_rest in ejabberd server. This module allow that you do HTTP request of terminal commands of ejabberdctl.

So it has "ejabberdctl connected_users", that return users online.

So in your model app using gem rest-client you can do something like it:

def online_users
    response = RestClient.post('http://localhost:5280/rest', "connected_users")
    response
end
0
Joe Hildebrand On

You will be much happier in the long run if you use a library like Strophe.js to do this in the browser, talking to an XMPP server that has BOSH enabled. Snapshots of presence are never anywhere as interesting as you expect them to be, and you're going to have really bad authentication/authorization problems on the path down which you're heading.