Set a variable messagingSenderId in service worker (Firebase) [duplicate] - variables

This question already has answers here:
Passing state info into a service worker before `install`
(2 answers)
Closed 5 years ago.
I would like to set a variable messagingSenderId value in my service worker, not an hardcoded one. Is it possible?
I register my service worker like this:
navigator.serviceWorker.register( 'firebase-messaging-sw.js' )
.then( function( registration ) {
messaging.useServiceWorker( registration );
});
And in my firebase-messaging-sw.js, I initialize firebase like this
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js' );
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js' );
firebase.initializeApp({
'messagingSenderId': 'my-id' // <- I want this to be variable
});
The problem is I can't find how to pass data to my service worker file. Any idea?
Thanks

As mentionned, Passing state info into a service worker before 'install' answered the question. Thanks.
Here is the answer for this use case:
You need to pass the variable in the URL like so:
var myId = 'write-your-messaging-sender-id-here';
navigator.serviceWorker.register( 'firebase-messaging-sw.js?messagingSenderId=' + myId )
.then( function( registration ) {
messaging.useServiceWorker( registration );
});
And then, in firebase service worker (firebase-messaging-sw.js), you can get this variable like so:
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js' );
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js' );
var myId = new URL(location).searchParams.get('messagingSenderId');
firebase.initializeApp({
'messagingSenderId': myId
});
This works. But URL.searchParams is a very new tool. It is less compatible than Firebase itself.
URL.searchParams: Chrome 51+, Firefox: 52+, Opera: unknown
Firebase: Chrome 50+, Firefox 44+, Opera 37+
So instead of:
var myId = new URL(location).searchParams.get('messagingSenderId');
I suggest using:
var myId = get_sw_url_parameters( 'messagingSenderId' );
function get_sw_url_parameters( param ) {
var vars = {};
self.location.href.replace( self.location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

Related

How to pass an array as a parameter to statementExecPromisified(statement,[]) function of sap-hdbext-promisfied in nodejs?

I have an array of users as below
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
I want to fetch data about the above users(if exists) from Hana database. I am using sap-hdbext-promisfied library in node.js.
My database connection is working fine. So, I am trying to execute a select query as below
async function readUsers(xsaDbConn){
try{
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
const checkuserexiststatement = await xsaDbConn.preparePromisified("SELECT USER_NAME FROM USERS WHERE USER_NAME IN (?)")
let checkuserexistresult = await xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr])
console.log(checkuserexistresult)
return checkuserexistresult
}catch(err){
console.log(err)
return;
}
}
Below is the output I get
PS C:\Users\Documents\XSA\SAC_POC\cap_njs> npm start
> cap_njs#1.0.0 start C:\Users\Documents\XSA\SAC_POC\cap_njs
> node server.js
myapp is using Node.js version: v12.18.3
myapp listening on port 3000
[]
I get an empty array object as output. This is not the expected output, instead it should provide details about the users as they exist in the database.
The above code works when I provide single user value instead of multiple users in an array as shown below
async function readUsers(xsaDbConn, tempxsahdbusers){
try{
let usersarr = 'SAC_XSA_HDB_USER_ABC'
const checkuserexiststatement = await xsaDbConn.preparePromisified("SELECT USER_NAME FROM USERS WHERE USER_NAME IN (?)")
let checkuserexistresult = await xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr])
console.log(checkuserexistresult)
return checkuserexistresult
}catch(err){
console.log(err)
return;
}
}
Output Of Above Code -
PS C:\Users\Documents\XSA\SAC_POC\cap_njs> npm start
> cap_njs#1.0.0 start C:\Users\Documents\XSA\SAC_POC\cap_njs
> node server.js
myapp is using Node.js version: v12.18.3
myapp listening on port 3000
[ 'SAC_XSA_HDB_USER_ABC' ]
So, why is it giving an empty array object when I provide an array as a parameter instead of a variable? Is it possible to provide an array as a parameter to the function statementExecPromisified(statement, []) of sap-hdbext-promisfied library in node.js ?
Your
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
has exactly one value, the String:
"'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"
When passing the userarr in the statementExecPromisified function as a parameter you are actually passing a nested array in an array. You could either try
xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr[0]])
or separate the values in the userarr and add multiple ? in the prepared statement and reference each single value with userarr[x].

Deepstream 1 - n relation

I'm trying to build a user notification using Deepstream.io. I'm using deepstream.io-storage-mongodb for storage. My data structure:
User
=================
id - email - others
Notication
=================
userId - notification
I'm try to implement 1-n modelling deepsteam tutorial. But I can't understand how can I do this. How can I store pointer or how can I point towards a List ? Or how can I implement notification using deepstream ?
Thanks in Advance.
you can try as like as given below (I'm using JS):
Receive Notication
var client = deepstream( 'localhost:6020' );
client.login();
// Unique Identification for user
let uniqueId = `userId:${userId}`;
// Mongodb collection : Notification
statusRecord = client.record.getList("Notification/" + uniqueId);
statusRecord.subscribe(function(data) {
data.forEach(function(name) {
var record = client.record.getRecord(name);
record.whenReady(function(r) {
// all notification
console.log( "r ==> ", r.get() );
});
});
});
Send Notification
const ds = deepstream( 'localhost:6020' );
ds.login();
// userId
const list = this.ds.record.getList( `Notification/${userId}` );
// id for notification
let id = `Notification/${this.ds.getUid()}`;
let record = this.ds.record.getRecord(id);
record.set( {
message: 'information'// save notification data
});
list.addEntry(id);
Hope it will solve your problem.

Issue with BTC-e API in App Script, method parameter

I am trying to incorporate the BTC-e.com API in to a google docs spreadsheet.
The API documentation is here: https://btc-e.com/api/documentation
The method name is sent via POST parameter method.
As the URLFetchApp requires me to set the type of request as POST by a parameter method and I then have another parameter called method to be set as getInfo.
How can I go about setting the fetch method as POST and have the API parameter method as getInfo.
Below is the function this relates too. Also I am sure there a more issues in my work I am yet to find.
function inventory() {
var nonce=Number(SpreadsheetApp.getActiveSheet().getRange('K2').getValue());
var token=SpreadsheetApp.getActiveSheet().getRange('K1').getValue();
var tokenEndpoint = "https://btc-e.com/tapi";
var sign= 'TEMP'
var head = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': token,
'Sign': sign
}
var params = {
method : "POST",
method : "getInfo",
headers: head,
contentType: 'application/x-www-form-urlencoded',
method : "getInfo",
nonce: nonce
}
var request = UrlFetchApp.getRequest(tokenEndpoint, params);
var response = UrlFetchApp.fetch(tokenEndpoint, params);
var response2=String(response);
SpreadsheetApp.getActiveSheet().getRange('K2').setValue(nonce+1);
SpreadsheetApp.getActiveSheet().getRange('I16').setValue(response2);
SpreadsheetApp.getActiveSheet().getRange('I17').setValue(nonce);
}
This just yields the error
Attribute provided with invalid value: method
Thanks,
Steve
PS: First time posting, I tried to get the format correct.
I made the following Google JavaScript function to do POST access to BTC-e. You can find this function in action in the example spreadsheet I made to demonstrate the BTC-e API functions.
function btceHttpPost(keyPair, method, params, nonce) {
if (keyPair === undefined) {
return "{'error':'missing key pair'}"
}
if (params === undefined) {
params = '';
}
// Cleanup keypair, remove all \s (any whitespace)
var keyPair = keyPair.replace(/[\s]/g, '');
// Keypair example: "AFE730YV-S9A4FXBJ-NQ12HXS9-CA3S3MPM-CKQLU0PG,96a00f086824ddfddd9085a5c32b8a7b225657ae2fe9c4483b4c109fab6bf1a7"
keyPair = keyPair.split(',');
var pubKey = keyPair[0];
var privKey = keyPair[1];
// As specified on the BTC-e api (https://btc-e.com/api/documentation) the
// nonce POST parameter must be an incrementing integer (>0). The easiest
// implementation is the use of a timestamp (TS), so there is no need
// for persistant storage. Preferable, the resolution of the TS should be
// small enough the handle the desired call-frequency (a sleep of the TS
// resolution can fix this but I don't like such a waste). Another
// consideration is the sizeof the nonce supported by BTC-e. Experiments
// revealed this is a 32 bit unsigned number. The native JavaScript TS,
// stored in a float, can be 53 bits and has a resolution of 1 ms.
if (nonce === undefined)
// This time stamp counts amount of 200ms ticks starting from Jan 1st, 2014 UTC
// On 22 Mar 2041 01:17:39 UTC, it will overflow the 32 bits and will fail
// the nonce key for BTC-e
var nonce = Math.floor((Date.now() - Date.UTC(2014,0)) / 200);
// Construct payload message
var msg = 'nonce=' + nonce + '&method=' + method + params;
var msgSign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, msg, privKey);
// Convert encoded message from byte[] to hex string
for (var msgSignHex = [], i = 0; i < msgSign.length; i++) {
// Doing it nibble by nibble makes sure we keep leading zero's
msgSignHex.push(((msgSign[i] >>> 4) & 0xF).toString(16));
msgSignHex.push((msgSign[i] & 0xF).toString(16));
}
msgSignHex = msgSignHex.join('');
var httpHeaders = {'Key': pubKey, 'Sign': msgSignHex};
var fetchOptions = {'method': 'post', 'headers': httpHeaders, 'payload': msg};
var reponse = UrlFetchApp.fetch('https://btc-e.com/tapi', fetchOptions);
return reponse.getContentText();
};
The problem looks to be with your params object . You have method set thrice in the same object, which is a source of confusion.
Next, take a look at the documentation for UrlFetchApp.fetch() ( https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object) ) . The method can take a value of post, get, delete, put.
The getInfo should probably be appended to your URL to make it
var tokenEndpoint = "https://btc-e.com/tapi/getInfo"
Per the docs, you also have to put in more parameters to the request, nonce, api key etc. Use this as a starting point, revisit the documentation and get back to SO if you still have trouble

Eventbrite API date range parameter for organizer_list_events

I need a way to search via the eventbrite api past events, by organizer, that are private, but I also need to be able to limit the date range. I have not found a viable solution for this search. I assume the organizer_list_events api would be the preferred method, but the request paramaters don't seem to allow for the date range, and I am getting FAR too many returns.
I'm having some similar issues I posted a question to get a response about parsing the timezone, here's the code I'm using to get the dates though and exclude any events before today (unfortunately like you said I'm still getting everything sent to me and paring things out client side)
Note this is an AngularJS control but the code is just using the EventBrite javascript API.
function EventCtrl($http, $scope)
{
$scope.events=[];
$scope.noEventsDisplay = "Loading events...";
Eventbrite({'app_key': "EVC36F6EQZZ4M5DL6S"}, function(eb){
// define a few parameters to pass to the API
// Options are listed here: http://developer.eventbrite.com/doc/organizers/organizer_list_events/
//3877641809
var options = {
'id' : "3588304527",
};
// provide a callback to display the response data:
eb.organizer_list_events( options, function( response ){
validEvents = [];
var now = new Date().getTime();
for(var i = 0; i<response.events.length; i++)
{
var sd = response.events[i].event.start_date;
var ed = response.events[i].event.end_date;
var parsedSD = sd.split(/[:-\s]/);
var parsedED = ed.split(/[:-\s]/);
var startDate = new Date(parsedSD[0], parsedSD[1]-1, parsedSD[2], parsedSD[3], parsedSD[4], parsedSD[5]);
var endDate = new Date(parsedED[0], parsedED[1]-1, parsedED[2], parsedED[3], parsedED[4], parsedED[5]);
if(endDate.getTime()<now)
continue;
response.events[i].event.formattedDate = date.toDateString();
validEvents.push(response.events[i])
}
if(validEvents.length == 0)
{
$scope.$apply(function(scope){scope.noEventsDisplay = "No upcoming events to display, please check back soon.";});
}
else
{
$scope.$apply(function(scope){scope.noEventsDisplay = "";});
}
$scope.$apply(function(scope){scope.events = validEvents;});
//$('.event_list').html(eb.utils.eventList( response, eb.utils.eventListRow ));
});
});
}

matching and verifying Express 3/Connect 2 session keys from socket.io connection

I have a good start on a technique similar to this in Express 3
http://notjustburritos.tumblr.com/post/22682186189/socket-io-and-express-3
the idea being to let me grab the session object from within a socket.io connection callback, storing sessions via connect-redis in this case.
So, in app.configure we have
var db = require('connect-redis')(express)
....
app.configure(function(){
....
app.use(express.cookieParser(SITE_SECRET));
app.use(express.session({ store: new db }));
And in the app code there is
var redis_client = require('redis').createClient()
io.set('authorization', function(data, accept) {
if (!data.headers.cookie) {
return accept('Sesssion cookie required.', false)
}
data.cookie = require('cookie').parse(data.headers.cookie);
/* verify the signature of the session cookie. */
//data.cookie = require('cookie').parse(data.cookie, SITE_SECRET);
data.sessionID = data.cookie['connect.sid']
redis_client.get(data.sessionID, function(err, session) {
if (err) {
return accept('Error in session store.', false)
} else if (!session) {
return accept('Session not found.', false)
}
// success! we're authenticated with a known session.
data.session = session
return accept(null, true)
})
})
The sessions are being saved to redis, the keys look like this:
redis 127.0.0.1:6379> KEYS *
1) "sess:lpeNPnHmQ2f442rE87Y6X28C"
2) "sess:qsWvzubzparNHNoPyNN/CdVw"
and the values are unencrypted JSON. So far so good.
The cookie header, however, contains something like
{ 'connect.sid': 's:lpeNPnHmQ2f442rE87Y6X28C.obCv2x2NT05ieqkmzHnE0VZKDNnqGkcxeQAEVoeoeiU' }
So now the SessionStore and the connect.sid don't match, because the signature part (after the .) is stripped from the SessionStore version.
Question is, is is safe to just truncate out the SID part of the cookie (lpeNPnHmQ2f442rE87Y6X28C) and match based on that, or should the signature part be verified? If so, how?
rather than hacking around with private methods and internals of Connect, that were NOT meant to be used this way, this NPM does a good job of wrapping socket.on in a method that pulls in the session, and parses and verifies
https://github.com/functioncallback/session.socket.io
Just use cookie-signature module, as recommended by the comment lines in Connect's utils.js.
var cookie = require('cookie-signature');
//assuming you already put the session id from the client in a var called "sid"
var sid = cookies['connect.sid'];
sid = cookie.unsign(sid.slice(2),yourSecret);
if (sid == "false") {
//cookie validation failure
//uh oh. Handle this error
} else {
sid = "sess:" + sid;
//proceed to retrieve from store
}