Browser notifications from server side using PHP - javascript

Can I send browser notifications from server to subscribed users using PHP? I saw this tutorial today, but that work only from client side. I know there are services like pushcrew, but I want to develop my own using PHP and JavaScript.
My actual requirement is asking users to confirm if I can send them notifications using this code,
if (Notification.permission !== "granted")
{
Notification.requestPermission();
}
then show notifications when I publish new article in my website.
NB: Browser support doesn't matter.

You have to trigger these notifications on the client side, so you need to get them from the PHP server to your JavaScript:
do an ajax polling every x seconds, for example with the jQuery ajax functions, and show a message if the server returned one
push the message over WebSockets, for example with Ratchet
Web Push allows you to push notification even if the user didn’t have the site open and is supported by the recent Firefox 44. It is partially supported in Chrome. For details check out the Mozilla Hacks blog.
Example with polling
JavaScript jQuery part:
function doPoll() {
// Get the JSON
$.ajax({ url: 'test.json', success: function(data){
if(data.notify) {
// Yeah, there is a new notification! Show it to the user
var notification = new Notification(data.title, {
icon:'https://lh3.googleusercontent.com/-aCFiK4baXX4/VjmGJojsQ_I/AAAAAAAANJg/h-sLVX1M5zA/s48-Ic42/eggsmall.png',
body: data.desc,
});
notification.onclick = function () {
window.open(data.url);
};
}
// Retry after a second
setTimeout(doPoll,1000);
}, dataType: "json"});
}
if (Notification.permission !== "granted")
{
// Request permission to send browser notifications
Notification.requestPermission().then(function(result) {
if (result === 'default') {
// Permission granted
doPoll();
}
});
} else {
doPoll();
}
JSON server answer in "test.json" if there is a message:
{
"notify": true,
"title": "Hey there!",
"desc": "This is a new message for you",
"url": "http://stackoverflow.com"
}
JSON server answer in "test.json" to not show a message:
{
"notify": false
}

Related

Using WebSocket to reconnect to server

I have an experimental task implemented in javascript that posts its data to the server via an ajax POST request. This POST request is mandatory for compatability with other tools.
Saving data works fine when the task is finished quickly but over a certain time the server times out and when the tasks tries the POST request, I get a 400 error and nothing gets saved.
My question is can I combine this with a WebSocket and use it to reconnect to the server occasionally and still post my data with an ajax POST request? If so, how do I do this?
This is what my POST function looks like:
$.ajax({
type: 'POST',
url: '/save',
data: {'data': JSON.stringify(mainData)},
success: function() {
console.log('success');
document.location = '/next'
},
// Endpoint not running, local save
error: function(err) {
if (err.status == 200) {
document.location = '/next'
}
}
});
Optimally I would like to have something like this
if (err.status == 200) {
document.location = '/next'
} else if (err.status == 400) {
// RECONNECT TO SERVER
// call ajax function again
}
I don't really have any experience with these tools, so any info will be much appreciated!
///////////////////// EDIT: ///////////////////////
I've been told that a more preferable option is to keep the connection constantly open with regular websocket requests. So a suggestion on how to do this would be appreciated as well.

How do I implement RPC using node to an existing RabbitMQ server with an existing exchange and queue

I am having problems implementing an RPC system using node/Javascript. So far I am able to fire off a message to the correct exchange and queue which then gets is able to be consumed by a consumer, but leaves my command line hanging without a response as to whether or not the message reached the broker and/or if the process completed.
I have a working producer and consumer in python using the pika library and following the RabbitMQ tutorials but can't get it to work with node.js.
This is my working code so far:
var amqp = require('amqp');
var connection = amqp.createConnection({
host: 'amqp://username:password#xx.xx.xx.xxx:5672'
}, {
defaultExchangeName: "myExchange"
});
var message = {
"key1": "value1",
"key2": "value2",
}
connection.on('ready', function() {
console.log("successful connection to host");
connection.exchange('myExchange', {
passive: true,
type: 'topic'
}, function(exchange) {
console.log(exchange.name); //this will output to console
connection.queue('myQueue', {
passive: true
}, function(queue) {
console.log(queue.name); //this will output to console
exchange.publish('myRoutingKey', message, {
contentType: 'application/json'
}, function() {
console.log("message sent") //this does NOT output to console
});
});
});
});
This will send the correct message and the consumer can use it to do what it needs to do.
My question is: how can I get a response back saying that Rabbit received the message?
My end game is here is to be able to loop through an array of messages and send them to my rabbit server so my consumers can process them.

Playframework Comet socket catch disconnect on client side

So I'm implementing an application that requires messages to be sent to the browser in real time. Currently this is working fine. When I receive a message I an Untyped Actor similar to the clock example.
What my issue is though is I would like to be able to reconnect the web page when the comet socket gets disconnected. Currently in chrome with comet sockets the loading icon continuously spins. Is there a way I can catch a disconnect message for the iframe/comet socket? Or is there something that I can poll in javascript/jquery? So i can then just reload the page?
If you want to reconnect "the web page" (in other words, make your browser send another request to server, with window.location.reload() or some other method), standard play.libs.Comet.onDisconnected handler is of no use to you - its domain is a server-side, not a client-side.
To make your client-side manage possible blackouts by itself, you may need to implement 'heartbeat' scheme. The client application will ping your server when too much time has been passed since the previous message. One possible way to do this:
var CometProcessor = {
processMessage: function(message) {
console.log(message);
},
handleHeartbeatTimeout: function() {
alert('Heartbeat process timeout');
},
handleHeartbeatError: function() {
alert('Heartbeat process error');
},
timeoutPeriod: 10000, // in milliseconds
timeoutId: 0, // will contain an ID of the current 'checking' timeout
checkHandler: null, // will contain a link to XHR object
checkBeat: function() {
// storing the reference to created XHR object:
this.checkHandler = $.ajax({
url: your_server_url,
// set it to the URL of ping script, that will respond instantly
timeout: 1000,
// this is configurable, but obviously it makes little sense setting this param
// higher than `timeoutPeriod`
success: $.proxy(function() {
// so this particular heartbeat request check went through ok,
// but the next may not be so lucky: we need to schedule another check
this.timeoutId = window.setTimeout(
$.proxy(this.checkBeat, this), this.timeoutPeriod);
}, this),
error: $.proxy(function(x, t) {
if (t === 'timeout') {
this.handleHeartbeatTimeout();
}
else {
this.handleHeartbeatError();
}
}, this)
});
},
message: function(message) {
// when we receive a message, link is obviously functioning,
// so we need to stop all the checking procedures
if (this.checkHandler) {
this.checkHandler.abort();
window.clearTimeout(this.timeoutId);
this.checkHandler = null;
}
processMessage(message); // this is where the actual processing takes place
// when we done with processing, we need to setup the heartbeat again:
this.timeoutId = window.setTimeout(
$.proxy(this.checkBeat, this), this.timeoutPeriod);
}
};
Leveraging this object at server-side is quite easy: you just have to replace the line similar to the one in this example...
Ok.stream(events &> Comet(callback = "parent.cometMessage"))
... with this:
Ok.stream(events &> Comet(callback = "parent.CometProcessor.message"))

Should I handle CODE using Javascript SDK FB.login POP-UP or is it handled automatically to gain the access_token?

In the authentication flow documentation here it mentions the CODE which is returned upon oAuth authentication.
Is this required for the Javascript SDK or is this handled automatically in the background in this code?
By "is this required?" I mean, do I have to handle this code to verify the authenticity of the request, or does the JavaScript SDK use the code automatically to gain the access_token.
The documentation explains the client side flow, and how to get the access token using the 'code' so until now. I've been assuming that the SDK manages this automatically in the background, because it produces an access code as response.authResponse.accessToken.
FB.login(function(response) {
if (response.authResponse) {
// User is logged in to Facebook and accepted permissions
// Assign the variables required
var access_token = response.authResponse.accessToken;
var fb_uid = response.authResponse.userID;
alert(dump(response.authResponse));
// Construct data string to pass to create temporary session using PHP
var fbDataString = "uid=" + fb_uid + "&access_token=" + access_token;
// Call doLogin.php to log the user in
$.ajax({
type: "POST",
url: "ajax/doLogin.php",
data: fbDataString,
dataType: "json",
success: function(data) {
// Get JSON response
if (data.result == "failure")
{
alert(data.error_message);
window.location.reload();
return false;
}
else if (data.result == "success")
{
window.location.reload();
return true;
}
},
error: function() {
return false;
}
});
} else {
// user is not logged in and did not accept any permissions
return false;
}
}, {scope:'publish_stream,email'});
I would like to know, because I want to ensure that my code is secure.
From the documentation
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).
If you plan on using the FB.api function to make calls to their Graph API, then you need the code to get the access token. But if you only need to authenticate the user, then what you have will do that just fine.

Is there a JavaScript API for sending notifications to Facebook users?

I am currently developing a Facebook application on a website that would need to send a notification to the app's users without using a user interface dialog. After reading some blogs I concluded that the option is available in example in PHP API only. I could only find this example:
http://developers.facebook.com/docs/channels/
Is there a JavaScript API to do this?
After some sort of more reading, I found out that FB.api could handle graph object apis and also the rest apis which are to be deprecated, and I got the following working:
FB.api('/1175241653/apprequests', 'post',
{ message: "This is a Good Request!!" },
function (response) {
if (!response || response.error) {
alert('Error occured , Request Failed :(( ');
} else {
alert('Request is sent successfully');
}
});
However, that id number 1175241653 does not work if the logged in user's id is not that id.
Therefore this would required the same functionaliy that Facebook uses to retrieve the ID of whomever signed into the application. Is there any way to do this?
Now , I got this working in all means and I'd like to share it with those who may deal with :))
lets say 1st as to do a single app request from ur application to any of facebook registered users in your application would be like this:
var data =
{
message: "Hey there, something good happened over here !",
access_token: "AAADdf39DLxgBANEwZA9ZCfZCSbtdfcZBtstWMMsW5JiZBjVW2Ucx234sedhHSZCm8aEABzvhWPBNWi1bTKwZBq0EcgZD"
}
FB.api('/68751034/apprequests',
'post',
data,
function (response) {
console.log(response);
if (!response || response.error) {
} else {
}
});
access_token should be provided as to authenticate the request from the application to the registered user.
If you do not know about access tokens, you can read about it over at the facebook site:
http://developers.facebook.com/docs/authentication/
Also, if you want to send batch requests to a set of users in one request call, there's a support page from the facebook site about that too:
http://developers.facebook.com/docs/reference/api/batch/
and here's a sample of what I mean :
var _batch = [];
for (var i = 0; i < _socialids.length; i++) {
_batch.push({
method: 'post',
relative_url: _socialids[i] + '/apprequests/?access_token=' + _accessTokens[i],
body: "message= This is a request sent to many users" });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// Do whatever when the batch request is sent
});
}

Categories