Firebase + Ionic Framework: Chat notifications - notifications

SO I am wondering if its possible to implement some sort of notifications with Firebase and Ionic Framework, which I am using to create app. Can I stick with Firebase only, or do I need to get some other service, such as for example Parse?
Thanks!
EDIT:
I got Parse working - awesome. THe only thing that doesnt really work for me is the following code:
function sendNotification(deviceToken, content){
console.log('targetDevice is: ' + deviceToken);
console.log('content is:' + content);
var notificationEndpoint = AY_Parse.parseEndpoint + "/1/push";
var headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': AY_Parse.parseApplicationId,
'X-Parse-REST-API-Key': AY_Parse.parseRestApiKey
};
var pushNotification = $resource(notificationEndpoint, {},
{
'save': {
method: 'PUT',
headers: headers
}
});
var registerNotification = new pushNotification();
registerNotification.deviceToken = deviceToken;
registerNotification.data = {alert: content};
console.log(registerNotification);
console.log(angular.toJson(registerNotification));
return registerNotification.$save;
}
It should send Push notificaiton to the targeted device, however it does nothing..
ANSWER:
Ok, the problem was with the following line:
registerNotification.deviceToken = deviceToken;
Changed to:
registerNotification.where= {deviceToken: deviceToken};

I'm unsure about Firebase but using Parse was easy to follow and understand, I managed to get everything working perfectly with the ngCordova Push Notifications.
https://parse.com/products/push
http://ngcordova.com/docs/plugins/pushNotifications/
https://www.parse.com/tutorials/ios-push-notifications
I hope these help.

Related

Apps Script PUT API

My goal is to update an API using Apps Script but I cannot work out how to do it. For simplicity sake here is my code:
let APIkey = "...";
let url = "..."
newData = {"stock_status": "instock"}
//Update API
The problem is I do not know how to get any further. I have read the relevant docs to this API but to no avail and I couldn't find anything about put requests in the Apps Script docs.
Answer:
You need to use UrlFetchApp.
Example:
I don't know how your API accepts authentication, but assuming it accepts the key as a URL parameter then you can do something like:
let APIkey = "..."
let url = "..."
const newData = {
"stock_status": "instock"
}
var options = {
'method' : 'PUT',
'contentType': 'application/json',
'payload' : JSON.stringify(newData)
}
UrlFetchApp.fetch(`${url}?key=${APIkey}`, options);
You can read the full documentation on fetch here

hapi 18 eventsourcing not working without stream.end()

Try to archive:
I try to use the HTML5 EventSourcing API https://developer.mozilla.org/de/docs/Web/API/EventSource to push events to my client application (javascript).
working example code with plain node http:
With a plain example node implementation it works perfectly and as expected. Example code: https://www.html5rocks.com/en/tutorials/eventsource/basics/
Problem:
When i try to integrate EventSourcing (or SSE) into my API endpoint which is based on hapi (currently using latest - 18.1.0) it does not work.
My route handler code mixed with some code i found:
const Stream = require('stream');
class ResponseStream extends Stream.PassThrough {
setCompressor (compressor) {
this._compressor = compressor;
}
}
const stream = new ResponseStream();
let data = 0;
setInterval(() => {
data++;
stream.write('event: message\n');
stream.write('data:' + data + '\n\n');
console.log('write data...', data);
// stream.end();
}, 1000);
return h
.response(stream)
.type('text/event-stream')
.header('Connection', 'keep-alive')
.header('Cache-Control', 'no-cache')
Findings:
I already searched and it seems since hapi 17.x there they exposed the flush method for the compressor < https://github.com/hapijs/hapi/issues/3658 >, section features.
But it still does not working.
They only way it sends a message is to uncomment the stream.end() line after sending the data. The problem obviously is that i cant send further data if i close the stream :/.
If i kill the server (with stream.end() line commented) the data gets transmitted to the client in a "single transmission". I think the problem is is still somewhere with the gzip buffering even when flushing the stream.
There are some code examples in the hapi github but i got none working with hapi 17 or 18 (all exmaples where hapi =< 16) :/
Someone know how to solve the problem or has a working EventSource example with latest hapi? I would kindly appreciate any help or suggestions.
Edit - Solution
The solution from the post below does work but i had also an nginx reverse proxy in front of my api endpoint it seems the main problem was not my code it was the nginx which had also buffered the eventsource messages.
To avoid this sort of problem add in your hapi: X-Accel-Buffering: no; and it works flawless
Well I just tested with Hapi 18.1.0 and managed to create a working example.
This is my handler code:
handler: async (request, h) => {
class ResponseStream extends Stream.PassThrough {
setCompressor(compressor) {
this._compressor = compressor;
}
}
const stream = new ResponseStream();
let data = 0;
setInterval(() => {
data++;
stream.write('event: message\n');
stream.write('data:' + data + '\n\n');
console.log('write data...', data);
stream._compressor.flush();
}, 1000);
return h.response(stream)
.type('text/event-stream')
}
and this is client code just to test
var evtSource = new EventSource("http://localhost/");
evtSource.onmessage = function(e) {
console.log("Data", + e.data);
};
evtSource.onerror = function(e) {
console.log("EventSource failed.", e);
};
These are the resources that where I found my way to working example
https://github.com/hapijs/hapi/blob/70f777bd2fbe6e2462847f05ee10a7206571e280/test/transmit.js#L1816
https://github.com/hapijs/hapi/issues/3599#issuecomment-485190525

Angularjs and Nodejs express

I'm trying to upload images through angularjs (client side) and Nodejs express (server side). I perfer not to use forms because my company does not work with it.
this is part of my controller-
$scope.uploadPhotoToServer = function () {
console.log('will upload to album ' + this.albumName + ' file ' + this.userPhoto);
var fd = new FormData();
//Take the first selected file
fd.append("file", this.userPhoto);
fd.append("album", this.albumName);
$http.post('/upload', fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
});
}]);
I wish if you could explain to me how this works and how I could continue
Thanks in advance :)
I'm not sure what you want to know, or what part you don't understand, but this basically just creates a $scope member function that adds the userPhoto and albumName to the FormData object (fd), which represents the form.The function then sends that object to the server using $http. You can think of the $http as a typical ajax command that just sends data to the server. (It actually uses the same XMLhttpRequest object that ajax does.
if you need it, here is a reference to the FormData() being used:
https://developer.mozilla.org/en-US/docs/Web/API/FormData

cordova/phonegap 3.3: how to set user credentials in fileUploadOptions

I'm trying to make a file upload via Phonegap 3.3 file transfer plugin to a windows server secured by base authentication. Actually the normal conversation between my app and the server (per ajax) is working perfectly by sending my user credentials with every ajax call.
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
'Authorization':authHeaderValue(db.getItem("user"), db.getItem("pass"))
};
and
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
This is what I tried so far (I found it on stackoverflow thread) but it gives me back a 401-unauthorized...
Pls. give me a short reply if you know something that could help me.
Best regards to you all,
Ingmar
Well, I do something similar but instead of "Basic" I use JWT for authentication. I'll show you the code I use:
options.headers = { 'Authorization': 'Bearer ' + app.session.getSess('token') };
And I use SessionStorage to save the token while it is valid.
If you wanna know about JSON Web Token
Another thing, remember to change the headers in your server, in my case something like:
('Access-Control-Allow-Origin','*');
('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
('Access-Control-Allow-Headers','Content-Type, Authorization, Content-Length, X-Requested-With');

Firefox add-on SDK: Get http response headers

I'm new to add-on development and I've been struggling with this issue for a while now. There are some questions here that are somehow related but they haven't helped me to find a solution yet.
So, I'm developing a Firefox add-on that reads one particular header when any web page that is loaded in any tab in the browser.
I'm able to observer tab loads but I don't think there is a way to read http headers inside the following (simple) code, only url. Please correct me if I'm wrong.
var tabs = require("sdk/tabs");
tabs.on('open', function(tab){
tab.on('ready', function(tab){
console.log(tab.url);
});
});
});
I'm also able to read response headers by observing http events like this:
var {Cc, Ci} = require("chrome");
var httpRequestObserver =
{
init: function() {
var observerService = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observerService.addObserver(this, "http-on-examine-response", false);
},
observe: function(subject, topic, data)
{
if (topic == "http-on-examine-response") {
subject.QueryInterface(Ci.nsIHttpChannel);
this.onExamineResponse(subject);
}
},
onExamineResponse: function (oHttp)
{
try
{
var header_value = oHttp.getResponseHeader("<the_header_that_i_need>"); // Works fine
console.log(header_value);
}
catch(err)
{
console.log(err);
}
}
};
The problem (and a major source of personal confusion) is that when I'm reading the response headers I don't know to which request the response is for. I want to somehow map the request (request url especially) and the response header ("the_header_that_i_need").
You're pretty much there, take a look at the sample code here for more things you can do.
onExamineResponse: function (oHttp)
{
try
{
var header_value = oHttp.getResponseHeader("<the_header_that_i_need>");
// URI is the nsIURI of the response you're looking at
// and spec gives you the full URL string
var url = oHttp.URI.spec;
}
catch(err)
{
console.log(err);
}
}
Also people often need to find the tab related, which this answers Finding the tab that fired an http-on-examine-response event