How to get the number of individual unread messages of PubNub? - objective-c

I'm using pubnub Services to add chat functionality to my App but i'm wondering if there is a way to get the individual number of unread messages. i'm using this link -> https://www.pubnub.com/docs/swift/data-streams-publish-and-subscribe

This can be accomplished using PubNub Functions. Functions are your own scripts that run automatically in the cloud when a message is published on one or many PubNub Channels.
It has a key-value store with increment, decrement, and retrieve functionality. This can be used very intuitively with an unread message pattern on PubNub.
Channel: room.*
Event: On-Before Publish
// Access to Distributed Database
const db = require('kvstore');
export default (request) => {
// Conventionally build the Key ID based on the request parameters and channel name.
let counterId = request.channels[0] + '/' + request.params.uuid;
// Increment or Decrement the unread message counter
let method = request.message.read ? -1 : 1;
// Increment/Decrement and read the unread message counter
return db.incrCounter( counterId, method ).then(()=>{
return db.getCounter(counterId).then((counter) => {
request.message.unread = counter || 0;
return request.ok();
});
});
}
Following this official guide you can integrate this new functionality into an existing app.

Related

Show private messages list of multiple users logged in at the same time

I've created a private messaging app where users login and can view their private messages. The problem that I am having is that is only shows the message list of one logged in user at a time. So let's say User A is logged in, it will show the chat list of user A. But then User B logs in, then both User A and User B will see the chat list of User B.
This is my server side call to fetch chats by user id:
Im using express for the backend
io.on('connection', socket => {
socket.on('findAllChatsByUserId', (userId) => {
socket.userId = userId
socket.join(socket.userId)
ChatModel.aggregate([{$match: {$or:[{senderId: userId},{receiver: userId}]}}, {$group: {_id: '$chatId', 'data': {$last: '$$ROOT'}}}]).exec(function(error, data) {
if (error) {
return error
} else {
data.sort(function (a, b) {
return b.data.date - a.data.date;
});
io.to(socket.userId).emit('findAllChatsByUserId', data);
}
})
})
});
And on the client side I do:
I am using VueJs on the FE
mounted () {
this.loading = true
this.socket.emit('findAllChatsByUserId', this.getUserId) // this calls the socket to get the chats for the given user Id
this.loading = false
},
I tried creating rooms by userId to make sure that only the data for a given user ID is passed in but it seems like only one user can use the socket at a time. I thought the rooms would solve this issue for me. Do I have to create a separate socket for each user? If so, how do I do that? I've followed the socket.io private messaging tutorial but they use 2 users talking to each other to explain the problem.
So I ended up solving this by doing:
io.to(socket.id).emit('findAllChatsByUserId', data);
instead of:
io.to(socket.userId).emit('findAllChatsByUserId', data);
So you use the "to" attribute to make sure the data you're sending is going to a particular socket, and you can find your specific socket by just calling socket.id (you don't have to set this, it gets set on its own. And the data will get emitted to whomever is on that specific socket.

In Twilio Programmable Chat, in Laravel backend, how to get members of a channel, given the channel code

How can I get the list of Twilio members of a channel, on my Laravel backend? I am using Programmable Chat API of Twilio. I tried using ChannelInstance members method or property, but I am not getting the list of members correctly. Is there a way to do this, from inside Laravel? I need it to be consumed by the iOS app on the other side (iOS app being the client). Ios app asks from Laravel the list of users that the user has chatted to, so I first get all channels:
$params = $request->all();
$username = $params["username"];
$unl = strlen($username);
$twilio = new Client($this->sid, $this->authToken);
// Get all user's channels
$ucs = $twilio->chat->v2->services($this->serviceId)
->users($username)
->userChannels
->read(50);
// Try to find members of each channel
foreach ($ucs as $uc) {
$channel = $twilio->chat->v2->services($this->serviceId)
->channels($uc->channelSid)
->fetch();
print_r($channel->toArray());
}
in the print_r - ed array, I have uniqueName and friendlyName, which are concatenated two participants of the channel. But I would prefer to just have two objects, or two strings that would tell me which are the members participants of that channel. Is there a way to do this?
Twilio developer evangelist here.
In this case you're just reading the information about the channel. Instead, you should fetch the members from the channel.
foreach ($ucs as $uc) {
$channel_members = $twilio->chat->v2->services($this->serviceId)
->channels($uc->channelSid)
->members
->read([], 20);
print_r($channel_members);
}
To get members, I needed to do this:
$ucs = $twilio->chat->v2->services($this->serviceId)
->users($username)
->userChannels
->read(50);
foreach ($ucs as $uc) {
$channel_members = $twilio->chat->v2->services($this->serviceId)
->channels($uc->channelSid)
->members
->read([], 20);
foreach ($channel_members as $record) {
print($record->sid . "\n");
}
}

Socket.io - Is there a way to save socketid to prevent a new one being generated

After a connection to the socket.io server a socket.id is given for the connection. When the socket connection has not been used after some time a new socket id is generated.
I have read a lot of tutorials that do a "hello world" connection that just gets you connected, but, there is not much literature on messaging peer-to-peer/group. The docs give a 3 line paragraph on rooms/namespaces and every question related to this is just given a link to the same 3 line paragraph.
I understand that you can create and object/array of chats(in this example). For this example, let's say it is an object. That Object looks something like this:
const connections = {
"randomSocketID1": {
recipient: "Mom",
messages: [Array of Objects]
//more information
}
}
I then send a message to randomSocketID1 --> 'Hello'. Then next day I want to send another message to "Mom". Is that socketID going to be the same OR AT LEAST will "randomSocketID1" be updated under the hood, to its updated ID(which sounds improbable)? Is the regeneration of the socketID a product of garbage collection or a socket/engine/websocket protocol?
thanks for any clarification
So I was still unable to find an actual answer to this and by the 0 responses i see that no one knows. So what I have done in order to make sure that user and socket id are maintained is whenever a user enters the component that connects to the socketio server an automatic 'update-user' is emitted and the back end then just finds the user and assigns it the value.
So I have something like this:
chat.component.ts:
ngOnInit(){
this.socket.emit('update-user', 'Ctfrancia');
}
then in the back end:
const users = {};
io.on('connection', socket => {
socket.on('update-user', user => {
if (user in users) users[user] = socket.id;
else users[user] = socket.id
});
});

Node.js client for wit.ai calls multiple custom actions

I'm trying to write an example app in wit.ai. I followed the quickstart app using node.js client that is shown at https://wit.ai/docs/quickstart.
The example shown there has only one custom action. But when I try to add a new story and a new action, I see that the context is being shared between the stories. This is causing wrong behaviour(a custom action from another story is being executed).
I cannot find any example with multiple custom actions and stories. Are there any node.js or python examples other than the ones from wit.ai websites?
You need to create a context for each session, and this is a quick example (from https://github.com/wit-ai/node-wit/blob/master/examples/messenger.js):
const findOrCreateSession = (fbid) => {
let sessionId;
// Let's see if we already have a session for the user fbid
Object.keys(sessions).forEach(k => {
if (sessions[k].fbid === fbid) {
// Yep, got it!
sessionId = k;
}
});
if (!sessionId) {
// No session found for user fbid, let's create a new one
sessionId = new Date().toISOString();
sessions[sessionId] = {
fbid: fbid,
context: { // New context per session id.
_fbid_: fbid
}
}; // set context, _fid_
}
return sessionId;
};
You can find a working example at https://github.com/hunkim/Wit-Facebook.
I suppose wit engine don't store context on their side.
You 'merge' function must merge entities in different ways, depending on your app logic.
But if you story is completed, you need to clear context for next stories.
I added a built-in function clear-context and call this function from wit as action.
Check out my example.
It's not an official api, but you can understand how wit http api works.

Can I use the same WebRTC channel for audio/video and file transfer?

I am a newbie to WebRTC. I am building an application that enables users to view each other's video stream, as well as exchange files. The audio/video part is implemented and working. The problem is I need to add the ability to exchange files now. I am using the below code to initialize the PeerConnection object
var connection = _getConnection(partnerId);
console.log("Initiate offer")
// Add our audio/video stream
connection.addStream(stream);
// Send an offer for a connection
connection.createOffer(function (desc) { _createOfferSuccess(connection, partnerId, desc) }, function (error) { console.log('Error creating session description: ' + error); });
_getConnection creates a new RTCPeerConnection object using
var connection = new RTCPeerConnection(iceconfig);
i.e., with no explicit constraints. It also initializes the different event handlers on it. Right after this, I attach the audio/video stream to this connection. I also cache these connections using the partner id, so I can use it later.
The question is, can I later recall the connection object from the cache, add a data channel to it using something like
connection.createDataChannel("DataChannel", dataChannelOptions);
And use it to share files, or do I have to create a new RTCPeerConnection object and attach the data channel to it?
You certainly do not have to create a another PeerConnection for file transfer alone. Existing PeerConnection can utilize RTCDatachannel with behaves like traditional websocket mechanism ( ie 2 way communication without a central server )
`var PC = new RTCPeerConnection();
//specifying options for my datachannel
var dataChannelOptions = {
ordered: false, // unguaranted sequence
maxRetransmitTime: 2000, // 2000 miliseconds is the maximum time to try and retrsanmit failed messages
maxRetransmits : 5 // 5 is the number of times to try to retransmit failed messages , other options are negotiated , id , protocol
};
// createing data channel using RTC datachannel API name DC1
var dataChannel = PC.createDataChannel("DC1", dataChannelOptions);
dataChannel.onerror = function (error) {
console.log("DC Error:", error);
};
dataChannel.onmessage = function (event) {
console.log("DC Message:", event.data);
};
dataChannel.onopen = function () {
dataChannel.send(" Sending 123 "); // you can add file here in either strings/blob/array bufers almost anyways
};
dataChannel.onclose = function () {
console.log("DC is Closed");
};
`
PS : while sending files over datachannel API , it is advisable to break down the files into small chunks beforehand . I suggest chunk size of almost 10 - 15 KB .