usage example of "sendDirectlyToAll" of simplewebrtc? - simplewebrtc

I am trying to send text to all my peers and I found this function "sendDirectlyToAll".
For your convenience, I put the function information here:
sendDirectlyToAll(channelLabel, messageType, payload) - broadcasts a
message to all peers in the room via a dataChannel.
string channelLabel - the label for the dataChannel to send on.
string messageType - the key for the type of message being sent.
object payload - an arbitrary value or object to send to peers.
I do not understand the meaning of 2nd and 3rd parameters. Could you kindly show me an example how to use this function?
Thanks
Derek

Here is my example showing how i managed to get it working:
/**
* send directly to all other peers
*/
oSimpleWebRTC.sendDirectlyToAll(
'meta', // sLabel
'info', // sType - will become oData.sType
{"foo": "bar"} // oData - will become oData.payload
);
/**
* Handle incoming dataChannel messages sent by "sendDirectlyToAll"
* #param {object} oPeer The Remote sending Peer Object
* #param {string} sLabel A Label, e.g.: 'meta'
* #param {object} oData Object containing the relevant Data
*/
oSimpleWebRTC.on('channelMessage', function (oPeer, sLabel, oData) {
// e.g. we want label "hark" to be ignored, as it fires continiously.
if ('hark' === sLabel) {
return true;
}
if ('meta' === sLabel) {
if ('info' === oData.type)
{
// do your stuff
console.log(oData.payload.foo);
}
}
}
Also, There are Answers to this question at the official SimpleWebRTC issues Tracker: https://github.com/andyet/SimpleWebRTC/issues/450
See my blog post to this example: https://blog.ueffing.net/post/2017/02/22/simplewebrtc-usage-example-of-senddirectlytoall/

Related

Binance API Withdrawal Error: "Signature for this request is not valid."

I'm facing an issue with the Binance API
Whenever I try to make a request for withdrawal, it returns "Signature for this request is not valid." error message, even though if with the same function I make a request for the account info, Funding balance, getAll balances or whatever, it works.
I already tried several solutions, but nothing seemed to work. This are some of my tries reading similar issues
Works with endpoints like "api/v3/account" or "sapi/v1/capital/config/getall"
Sending the signature and the params in the body (it returns "You are not authorized to execute this request" error message, I think is because is not reading the body, only query params)
Activate all permissions for the API, and check the API
Send in the query the param "name"
Using Node packages like node-binance-api (It's not up to date with the request for withdrawals)
Changing scripts in librery node-binance-api to the actual api for withdrawals (same error as doing it myself)
I'm using NodeJs, axios to make the requests. This is my function:
/**
* Send Request to withdraw USDT funds from the selected wallet to a specified address
* #param wallet
* #param amount
* #param address
* #returns
* #link https://binance-docs.github.io/apidocs/spot/en/#withdraw-user_data
*/
makeWithdrawal(
wallet: WalletType = 'SPOT',
amount: number,
address: string
) {
const walletIndex = WalletEnum[wallet];
return this.makeRequest<{ id: string }>(
'sapi/v1/capital/withdraw/apply',
'POST',
{
coin: 'USDT',
amount,
wallet: walletIndex,
address,
network: 'TRX',
name: '_'
}
);
}
/**
* Makes Request to Binance Pay API
* #param endpoint
* #param method
* #param params
* #returns
* #link https://binance-docs.github.io/apidocs/spot/en
*/
private makeRequest<T>(
endpoint: string,
method: Method = 'GET',
params: {[key: string]: string | number} = {}
): Promise<T> {
const timestamp = Number(new Date().getTime()).toFixed(0);
let query = `timestamp=${timestamp}`;
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
const value = params[key];
query += `&${key}=${value}`
}
}
const signature = this.sign(query);
const headers: AxiosRequestHeaders = {
'X-MBX-APIKEY': process.env.BINANCE_API_KEY,
};
const requestObservable = this.httpService.request<T>({
method,
url: `${process.env.BINANCE_API_URL}/${endpoint}`,
params: {...params, timestamp, signature},
headers
}).pipe(
map(res => res.data)
);
return lastValueFrom(requestObservable);
}
/**
* Signs payload with private key
* #param payload
* #returns
*/
private sign(query: string) {
return createHmac('sha256', process.env.BINANCE_API_SECRET)
.update(query)
.digest('hex');
}
I really can't understand what is going, if someone could please help me to solve this, as I'm reading this is a common issue, but I really tried solutions and no hope.
Thank you
For anyone having this problem, the issue was that I was sending the request inside the "params" instead of the url, weirdly enough, it didn't proccess it correctly, so make this small change:
const requestObservable = this.httpService.request<T>({
method,
url: `${process.env.BINANCE_API_URL}/${endpoint}?${query}&signature=${signature}`,
headers
}).pipe(
map(res => res.data)
);
And you are good to go

Amazon Pinpoint Endpoints in putEvents-Method of the JavaScript SDK aren't working

I've built a AWS Pinpoint integration into my app using API Gateway and Events are properly coming into Pinpoint. However with every new request a new Endpoint is created although I supply the "address"-field.
I went through all the docs provided by AWS:
https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-events.html
https://docs.aws.amazon.com/pinpoint/latest/developerguide/integrate-events.html
Primarily used this class doc which seems to have some missing info:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Pinpoint.html
async function putEvent(clientRequest){
/* create the putEvents parameters */
var param = {
ApplicationId: PINPOINT_APP_ID,
EventsRequest: {
BatchItem: { }
}
};
/* create the event parameter */
var eventParam = {
Endpoint: {
Address: clientRequest.deviceId,
ChannelType: 'CUSTOM',
Demographic: {
AppVersion: clientRequest.app.version,
Locale: clientRequest.system.locale,
Make: clientRequest.device.manufacturer,
Model: clientRequest.device.model,
ModelVersion: clientRequest.device.version,
Platform: clientRequest.platform.name,
PlatformVersion: clientRequest.platform.version
}
}
};
/* add the location if its was provided */
if(clientRequest.hasOwnProperty('location')){
/* add the latitude and longitude values */
eventParam.Endpoint['Location'] = {
Latitude: clientRequest.location.latitude,
Longitude: clientRequest.location.longitude
}
/* check if a city and postal code was supplied
alongside the country value */
if(clientRequest.location.hasOwnProperty('cityName') == true
&& clientRequest.location.hasOwnProperty('countryCode') == true
&& clientRequest.location.hasOwnProperty('postalCode') == true){
/* attach to the location param */
eventParam.Endpoint.Location['Country'] = clientRequest.location.countryCode;
eventParam.Endpoint.Location['City'] = clientRequest.location.postalCode;
eventParam.Endpoint.Location['PostalCode'] = clientRequest.location.cityName;
}
}
/* check if the userId was supplied */
if(clientRequest.hasOwnProperty('userId')){
/* attach the hashed and salted user id */
eventParam.Endpoint['User'] = {UserId: getSHA512(clientRequest.userId+USERID_HASHSALT)};
}
/* attach the event values */
eventParam['Events'] = [{
EventType: clientRequest.event.name,
Timestamp: (new Date()).toISOString()
}];
/* create a unique request id */
var requestId = (new Date().getTime()) + Math.floor(Math.random() * 10);
param.EventsRequest.BatchItem[requestId] = eventParam;
/* flush an event to Pinpoint */
await Pinpoint.putEvents(param).promise();
}
After every request I do have a new Pinpoint Endpoint defined, although I provide a unique Address-value for each Endpoint.
a) What do I need to do have the Endpoints unique?
b) How can I report Sign-ins, Sign-out and the other Events?
^ Could not find them in the documentation
Agreed the Pinpoint docs / class document is incomplete leaving out desired information. From my experiencing testing & using the API this is what I have found which hopefully can be of use.
a) What do I need to do have the Endpoints unique?
Pinpoint.putEvents not only creates a new event for an endpoint but it also creates or updates endpoint data
The fact that Pinpoint.putEvents can create or update an endpoint is causing the error you've encountered where a new endpoint is created after every event request.
This is because you are accidentally creating a new endpoint equal to the random requestId for each event that you send when setting the keys of BatchItem. The object keys of BatchItem are actually supposed to be the endpointId the event is supposed to be associated with opposed to the requestId for the event (This is not mentioned at all in the docs!)
To keep endpoints unique you first need to know what the unique endpoint is for the user in addition to the address and unique UserId (This seems to be missing from pinpoint docs. I realized it when trying to update or delete an endpoint which you cannot do by address as you need the endpointId). From your example I would choose something related to the userId concatenated with the channel type if you plan on having multiple channels for a single user as pinpoint does allow messages to be sent through email, sms and recorded voice calls (you've listed "CUSTOM" but I'd try to use one of the enum's that is actually associated with how the message would be delivered. I believe this allows this endpoint to work better with different types of pinpoint campaigns and journeys to send messages to your users)
// Original code adding eventParam to param.EventsRequest.BatchItem incorrectly by random requestId
var requestId = (new Date().getTime()) + Math.floor(Math.random() * 10);
param.EventsRequest.BatchItem[requestId] = eventParam;
// correct code associating eventParam with a unique endpointId
var endpointId = eventParam.Endpoint.User.UserId+'CUSTOM'
param.EventsRequest.BatchItem[endpointId] = eventParam;
Additionally keep in mind that all of the information you have added to eventParam.endpoint will update / overwrite whatever is currently stored for those endpointId attributes when calling Pinpoint.putEvents so watch out for that
b) How can I report Sign-ins, Sign-out and the other Events?
I believe to report sign-ins / sign-outs that are visualized in the pinpoint dashboard follow the event naming convention in the Pinpoint app events documentation
so for sign-ins the event name is _userauth.sign_in
I don't think sign outs are displayed automatically on the Anlaytics -> Usage dashboard but you can use any consistent event name for sign outs and then use pinpoint filters to see those events through time.

Send JSON message to Azure Queue storage

I am using azure-storage node module.
I would like to send JSON on my queue and get it into my queue on azure function.
I send message in queue. I stringify my message to put in queue.
// This is my service who send message to queue via node lib azure-storage
const queueMsg = {
userId,
token: tokenNotif
};
queueSvc.createMessage(Config.REGISTRATION_FCM_PUSH_NOTIFICATION_QUEUE, JSON.stringify(queueMsg), (err) => {
if (!error) {
this._logger.info(`User ${userId} has register this push notification token`);
resolve(true);
} else {
reject(false);
}
});
And in the queue function i have an error because the function think isn't a string and push the message text on xx-queue-poison
{"userId":"a6c8a103-dacc-4b15-bffd-60693105f131","token":"xxxx"}
I don't know why the quote is replaced by ASCII code on queue ?
I have tested something else!
From my service i call a Http Azure function, and this function call the Queue Storage and it's work by this way :s ..
The HttpTrigger function call queue
context.bindings.notificationQueue = [{ userId: name, token }];
And queue received data
context.log(`Received userId ${queueItem.userId} :: ${queueItem.token}`);
Why by using HttpTrigger function to QueueTrigger function it's working, but when i am using the lib "azure-storage" is not working ?
Thx
I don't know why the quote is replaced by ASCII code on queue ?
Basically the SDK is converting the string message to make it XML safe. If you look at the code in the SDK, by default it uses TextXmlQueueMessageEncoder as the message encoder. The encode function replaces " with " to make it XML safe.
From the SDK code (partial code snippets):
QueueService.prototype.createMessage = function (queue, messageText, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createMessage', function (v) {
v.string(queue, 'queue');
v.queueNameIsValid(queue);
v.callback(callback);
});
var xmlMessageDescriptor = QueueMessageResult.serialize(messageText, this.messageEncoder);
function TextXmlQueueMessageEncoder(){
}
util.inherits(TextXmlQueueMessageEncoder, QueueMessageEncoder);
/**
* Encode utf-8 string by escaping the xml markup characters.
* #this TextXmlQueueMessageEncoder
*
* #param {string} [input] The target to be encoded.
*
* #return {string}
*/
TextXmlQueueMessageEncoder.prototype.encode = function(input){
return input.replace(/&/gm, '&')
.replace(/</gm, '<')
.replace(/>/gm, '>')
.replace(/"/gm, '"')
.replace(/'/gm, '&apos;');
};
One possible solution would be to convert the string to a base64 encoded string as you suggested. However if you're using the SDK to retrieve the messages, you should not see these " in your message body as the SDK takes care of decoding the message.

Sending Emails with Gmail API

I'm currently working on hooking into the Gmail API using NodeJS. I have a working connection and can access my messages and such, but I'm having difficulty actually sending email with the API. Here is what I have below:
/**
* Send Message.
*
* #param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #param {String} email RFC 5322 formatted String.
* #param {Function} callback Function to call when the request is complete.
*/
function sendMessage(userId, email, callback, auth) {
// Using the js-base64 library for encoding:
// https://www.npmjs.com/package/js-base64
//var base64EncodedEmail = Base64.encodeURI(email);
var base64EncodedEmail = Buffer.from(email).toString('base64');
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'resource': {
'raw': base64EncodedEmail
}
});
request.execute(callback);
}
This is from the official documentation (here), for the most part. I'm calling the function as such:
authorize(JSON.parse(content), sendMessage('me', btoa('This is a test')));
The error I'm getting is this:
var request = gapi.client.gmail.users.messages.send({
^
ReferenceError: gapi is not defined
at sendMessage (D:\Documents\Web Programming\React\neis-guy-painting\src\Server\Node\gmail.js:148:17)
at fs.readFile (D:\Documents\Web Programming\React\neis-guy-painting\src\Server\Node\gmail.js:23:34)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
I realize that this is because I don't have gapi defined, but I can't seem to figure out what that actually should be.
What am I missing here?

Update solr collection using solr-client

I'm using the solr-client module for nodejs to query my solr collections.
Now I'm trying to add to and update collections in my backend code using solr-client.
I've tried http://lbdremy.github.io/solr-node-client/code/add.js.html succesfully to add data to a collection. But I don't know how to update records.
I've tried using this method (all methods can be found here: http://lbdremy.github.io/solr-node-client/code/solr.js.html);
/**
* Send an update command to the Solr server with the given `data` stringified in the body.
*
* #param {Object} data - data sent to the Solr server
* #param {Function} callback(err,obj) - a function executed when the Solr server responds or an error occurs
* #param {Error} callback().err
* #param {Object} callback().obj - JSON response sent by the Solr server deserialized
*
* #return {Client}
* #api private
*/
Client.prototype.update = function (data, callback) {
var self = this;
this.options.json = JSON.stringify(data);
this.options.fullPath = [this.options.path, this.options.core, 'update/json?commit=' + this.autoCommit + '&wt=json']
.filter(function (element) {
if (element) {
return true;
}
return false;
})
.join('/');
updateRequest(this.options, callback);
return self;
}
But how does this method knows which records to update? Does it searches for pk's in the data parameter and when it matches with your pk in the collection, it get's updated? And does it need an extra commit?
But how does this method knows which records to update? SEE BELOW
Does it searches for pk's in the data parameter and when it matches with your pk in the collection, it get's updated? - YES
And does it need an extra commit? - YES
Technically, u can use the INSERT as well as UPDATE. They are the same in SOLR

Resources