I use pusher to implement real-time chat and notifications in my website. Users are allowed to start conversation(chat) with others and conversation can be only 1 on 1.
Messages are also stored in db so that user could have chat history as well.
I user with userId=14 has three active conversation I would generate JS script in php that would connect him to pusher and subscribe for three presence-channels representing each of three conversations. Every channel has events like "new-msg" etc. Everything work great - users get message if chat window is open or notification badge if not.
The problem starts when another user want to start a new conversation with userId=14. There is no private or presence channel for that. If I used public channel then every logged in user would get notified which is not good.
What I do know is that once logged in my website users connect to pusher and additionally to already active presence-channels subsribe to public channel "new-conversations" but every user waits for specific event which represents his userId.
var pusher = new Pusher('APP_KEY');
var channel = pusher.subscribe('new-conversations');
channel.bind(userId,
function(data) {
// subscribes to new presence-channel using information from data variable
}
);
When another user wants to start conversation with userId=14 he makes ajax call to server where PHP script generates event representing userId=14 containing data about himself and sends it to every connected(logged in) user but only userId=14 is waiting for this. Once triggered userId=14 can subsribe to new presence-channel.
While all this scenario works, I was wondering if there is some better, more cleaner out-of-the-box solution to this situation? I have read through pusher documentation but found nothing but I refuse to except that pusher developrs havent though about it.
POSSIBLE SOLUTION
I though of another solution. Every user should subscribe to presence-channel var channel = pusher.subscribe('presence-14');
where 14 = userId. If userId= 39 wants to start conversation with him he would send userId=14 to server and server would send userId=39 to channel "presence-14". Is that it?