Is there any way to use our own server for storage of data generated using PUBNUB api? [duplicate] - pubnub

I'm looking to develop a chat application with Pubnub where I want to make sure all the chat messages that are send is been stored in the database and also want to send messages in chat.
I found out that I can use the Parse with pubnub to provide storage options, But I'm not sure how to setup those two in a way where the messages and images send in the chat are been stored in the database.
Anyone have done this before with pubnub and parse? Are there any other easy options available to use with pubnub instead of using parse?

Sutha,
What you are seeking is not a trivial solution unless you are talking about a limited number of end users. So I wouldn't say there are no "easy" solutions, but there are solutions.
The reason is your server would need to listen (subscribe) to every chat channel that is active and store the messages being sent into your database. Imagine your app scaling to 1 million users (doesn't even need to get that big, but that number should help you realize how this can get tricky to scale where several server instances are listening to channels in a non-overlapping manner or with overlap but using a server queue implementation and de-duping messages).
That said, yes, there are PubNub customers that have implemented such a solution - Parse not being the key to making this happen, by the way.
You have three basic options for implementing this:
Implement a solution that will allow many instances of your server to subscribe to all of the channels as they become active and store the messages as they come in. There are a lot of details to making this happen so if you are not up to this then this is not likely where you want to go.
There is a way to monitor all channels that become active or inactive with PubNub Presence webhooks (enable Presence on your keys). You would use this to keep a list of all channels that your server would use to pull history (enable Storage & Playback on your keys) from in an on-demand (not completely realtime) fashion.
For every channel that goes active or inactive, your server will receive these events via the REST call (and endpoint that you implement on your server - your Parse server in this case):
channel active: record "start chat" timetoken in your Parse db
channel inactive: record "end chat" timetoken in your Parse db
the inactive event is the kickoff for a process that uses start/end timetokens that you recorded for that channel to get history from for channel from PubNub: pubnub.history({channel: channelName, start:startTT, end:endTT})
you will need to iterate on this history call until you receive < 100 messages (100 is the max number of messages you can retrieve at a time)
as you retrieve these messages you will save them to your Parse db
New Presence Webhooks have been added:
We now have webhooks for all presence events: join, leave, timeout, state-change.
Finally, you could just save each message to Parse db on success of every pubnub.publish call. I am not a Parse expert and barely know all of its capabilities but I believe they have some sort or store local then sync to cloud db option (like StackMob when that was a product), but even if not, you will save msg to Parse cloud db directly.
The code would look something like this (not complete, likely errors, figure it out or ask PubNub support for details) in your JavaScript client (on the browser).
var pubnub = PUBNUB({
publish_key : your_pub_key,
subscribe_key : your_sub_key
});
var msg = ... // get the message form your UI text box or whatever
pubnub.publish({
// this is some variable you set up when you enter a chat room
channel: chat_channel,
message: msg
callback: function(event){
// DISCLAIMER: code pulled from [Parse example][4]
// but there are some object creation details
// left out here and msg object is not
// fully fleshed out in this sample code
var ChatMessage = Parse.Object.extend("ChatMessage");
var chatMsg = new ChatMessage();
chatMsg.set("message", msg);
chatMsg.set("user", uuid);
chatMsg.set("channel", chat_channel);
chatMsg.set("timetoken", event[2]);
// this ChatMessage object can be
// whatever you want it to be
chatMsg.save();
}
error: function (error) {
// Handle error here, like retry until success, for example
console.log(JSON.stringify(error));
}
});
You might even just store the entire set of publishes (on both ends of the conversation) based on time interval, number of publishes or size of total data but be careful because either user could exit the chat and the browser without notice and you will fail to save. So the per publish save is probably best practice if a bit noisy.
I hope you find one of these techniques as a means to get started in the right direction. There are details left out so I expect you will have follow up questions.
Just some other links that might be helpful:
http://blog.parse.com/learn/building-a-killer-webrtc-video-chat-app-using-pubnub-parse/
http://www.pubnub.com/blog/realtime-collaboration-sync-parse-api-pubnub/
https://www.pubnub.com/knowledge-base/discussion/293/how-do-i-publish-a-message-from-parse
And we have a PubNub Parse SDK, too. :)

Related

Shopify Webhook Real Time changing

is there an api on shopify where I can see real time when data changes ? Maybe I have a node server and I use sockets to see when anyone has bought anything from my shop that I get a notification via nodejs on my backend. is it possible ? a few websites has this, they offers you to sell on their site and you can see real time changes data when anything was bought
Yes, you can subscribe to multiple Webhooks to get notified when a change occurs on your shop. Using the REST Admin API, available webhook event topics include:
orders/create: occurs whenever an order is created / someone buys from your shop.
orders/paid: occurs whenever an order is paid.
orders/fulfilled: occurs whenever an order is fulfilled.
orders/cancelled: occurs whenever an order is cancelled.
Use the /admin/api/2023-01/webhooks.json endpoint to subscribe to a webhook:
// Node.js - Session is built by the OAuth process
const webhook = new shopify.rest.Webhook({session: session});
webhook.topic = "orders/create";
webhook.address = "https://example.hostname.com/";
// format you want to receive the event data in
webhook.format = "json"; // or XML
// fields you want to receive
webhook.fields = [
"id",
"note"
];
await webhook.save({
update: true,
});
You can also use the GraphQL Admin API for the same purpose.

How do I provide real time update in nodejs?

I am working on an e-commerce site. There are times where a product would no longer be available but the user would have added it to the cart or added to their saved items. How do I implement the feature such that if the product has been updated, the user would be notified as soon as possible?
I thought about doing a cron job that would check the status of the product if it still available or has been recently updated. But I do not know if that is feasible. I am open to better ideas
Thanks
Similar images are included below
What you are trying to achieve falls into real-time updates category and technically there would be more than one option to achieve this.
The chosen solution would depend on your application architecture and requirements. Meanwhile, I can suggest looking into Ably SDK for Node.js which can offer a good starter.
Here down a sample implementation where on the back-end you will be publishing messages upon item's stock reaching its limit:
// create client
var client = new Ably.Realtime('your-api-key');
// get appropriate channel
var channel = client.channels.get('product');
// publish a named (may be the product type in your case) message (you can set the quantity as the message payload
channel.publish('some-product-type', 0);
On the subscriber side, which would be your web client, you can subscribe to messages and update your UI accordingly:
// create client using same API key
var client = new Ably.Realtime('your-api-key');
// get product channel
var channel = client.channels.get('product');
// subscribe to messages and update your UI
channel.subscribe(function (message) {
const productName = message.name;
const updatedQuantity = message.data;
// update your UI or perform whatever action
});
Did a live betting app once and of course live updates are the most important part.
I suggest taking a look into websockets. The idea is pretty straight forward. On backend you emit an event let's say itemGotDisabled and on frontend you just connect to your websocket and listen to events.
You can create a custom component that will handle the logic related to webscoket events in order to have a cleaner and more organized code an you can do any type of logic you want to updated to component as easy as yourFEWebsocketInstance.onmessage = (event) => {}.
Of course it's not the only way and I am sure there are packages that implements this in an even more easy to understand and straight forward way.

How to retrieve all user tokens and send FCM to all

I am trying to send a FCM to multiple users at a time. I can't seem to find a clear answer other than using a topic but i have several conditions which make this quite difficult on my side. Is it at all possible to extract all tokens from a particular document (similar to setting it up as a topic but based on my logic) and pass that array to the Cloud function?
My current code is as follows and it works for a single user (i am only posting the part where the token is extracted):
return admin.firestore().doc('Seller_tokens/tokens/' + brand + '/wc').get().then(usertokensdoc =>{
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
const payload = {
data:{
title:'FCM - Test',
content: 'FCM - This is a test message,
},
token: sellertokenID
};
for the line:
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
I do not want to specify a single userid, where the 'userid' is the field in the document . And hence I would like to pass an array, if possible.
As you mentioned and as clarified in the official documentation Send messages to multiple devices, there are only two ways of sending messages to multiple tokens:
Firebase Cloud Messaging provides these two ways to target a message to multiple devices:
Topic messaging, which allows you to send a message to multiple devices that have opted in to a particular topic.
Device group messaging, which allows you to send a message to multiple devices that belong to a group you define.
In addition to this, as mentioned in this other question here, there is no API for you to get all tokens at once, so, you will need to get the individually for usage.
So, to summarize, there is not an automatic way of getting the tokens, but once you get them, I believe using the Device Messaging way would be better for you, since you can define specific groups to receive the FCM, per tokens that you retrieved.
Let me know if the information helped you!
you can retrieve the token documents based on your conditions in cloud function. loop through them, create an array of tokens and pass them to Firebase messaging as below
admin.messaging.sendToDevice(tokens, payload). below url has a very good example.
FCM - Cloud Functions Example

Progressive Web Application receiving data to trigger notification

Hello i'm newbie and im hardly to understand this notification in service-worker, and because my knowledge isn't good yet then probably i will unable to explain my problem clearly.
so here's the code :
// triggered everytime, when a push notification is received.
self.addEventListener('push', function(event) {
console.info('Event: Push');
var title = 'New commit on Github Repo: RIL';
var body = {
'body': 'Click to see the latest commit',
'tag': 'pwa',
'icon': './images/48x48.png'
};
event.waitUntil(
self.registration.showNotification(title, body)
);
});
this is the code that trigger to POP the notification, what I do not understand is where the argument to accept/ receive the data ?
I've been searched a lot: https://auth0.com/blog/introduction-to-progressive-web-apps-push-notifications-part-3/ ,
https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web
there's some new data JSON or from git-server or push api, but I still hardly to understand where's to accept the data.
sorry if you still do not understand what's my problem.
Here to make it simple what I want :
Let's say i make a button, and everytime i click the button it will value as 'True' and I want that 'True' value to pass into argument and trigger the push of notication in service-worker.
2nd questions: am I able to trigger notification with header or text in html ? since we can manipulate the text with DOM ?
am I able to trigger notification without GCM, or API cause I just want a simple notification in serivce-worker like above without passing much data.
If you give more advice or maybe notification without service-worker but real time , I am surely happy to read it but I hope Im able to understand.
There are basically two concepts involved that work well together but can be used independently. The first is the visible UI shown to a user that tells them information or prompts them for an action. The second is sending an event from a server to the browser without requiring the user to currently be active on the site. For full details I recommend reading Google's Web Push docs.
Before either of those scenarios you have to request permission from the user. Once permission is granted you can just create a notification. No server or service worker required.
If you want to send events from a server you will need a service worker and you will need to get a subscription for the user. Once you have a subscription you would send it to a server for when you want to send an event to that specific browser instance.
Once you receive a push event from a server you display the UI the same as in the first scenario except you have to do it from the service worker.

Getting customized message from GCM using Web push notifications

I'm using Web push notifications with Chrome, and they work great. But now I want to deliver a custom message in my notifications. I can have my Service Worker call out to my site to get content, as is done at https://simple-push-demo.appspot.com/—which is fine if I want every recipient to see the same message.
Is there any way to get either the recipient’s registration_id or the message_id that GCM returns? If I could get either of these and include them in the callback to the service, I could customize the response.
Also, any info on when we might be able to include a payload in the call to GCM?
The registration_id and message_id fields aren't exposed, but if the user is previously authenticated to your app, any fetch() to the server from your Service Worker will include credentials (and session information) which you can use to identify them.
If that doesn't work for your case, you can store user/session information in IndexedDB.
Payloads are coming soon—likely Chrome 50 or 51—based on the Web Push protocol. It's a bit of extra overhead and work to configure the (required) encryption.
It's possible, but I wouldn't do it since it's specific to GCM, while other browsers use other services.
You can either create a unique ID for each user (like we're doing in Mercurius) and store it in IndexedDB, or you can use the entire endpoint URL as an ID.
Here's the snippet to get the registration_id:
self.registration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
var endpoint = subscription.endpoint;
var endpointParts = endpoint.split('/');
var gcmRegistrationID = endpointParts[endpointParts.length - 1];
console.log(gcmRegistrationID);
}
});
P.S.: It returns a promise, so make sure your service worker waits for the promise to be resolved.

Resources