socket.emit only emitting to emitter - javascript

I am using react-native with socket.io to send and receive contact requests but my code is only emitting to the emitter and to no one else.
This is the server side:
users = []; // Each time a new user joins the server they are saved in this array
socket.on('create connection', function(data, callback) {
if(data.receiverId in users) { // If the user you want to add is online then callback is true else callback is false
// The underneath line is the one that I will be using but nothing happend
//io.sockets.in(data.receiverId).emit('save room', data);
// So I created this one to see if I actually was emitting something
socket.emit('save room', data); // I found out that the emitting was working but only with the emitter
callback(true);
}else
callback(false);
});
So my conclusion is that my server side is correct and the problem lies on my client side
This is my client side:
constructor() {
this.socket = SocketIOClient('http://192.168.15.4:8000');
this.socket.on('save room', function (data) { // This is where the server calls the emit. It was at first inside the connect function but I moved it to the constructor to see if that way all clients could get it, results are the same
Alert.alert(
'Accept Connection?',
'User: '+data.emitterId+' sent you a connection request',
[
{
text: 'Accept',
onPress: () => {},
},
{
text: 'Refuse',
onPress: () => {},
},
],
{cancellable: false}
);
})
}
#action connect(data, callback1) { // this access the function we had previously in the server
this.socket.emit('create connection', data, function (callback2) {
if(!callback2)
Alert.alert(
'User Offline',
'This user is currently offline try again later',
[
{
text: 'OK',
onPress: () => {callback1(false)},
},
],
{cancellable: false}
);
else {
callback1(true)
}
});
}
I think the problem lies on where I place the this.socket.on('save room') function, but in react-native I really do not know where to put it.

Thanks to #H. Tugkan kibar and #azium I realized that the problem was on my server side the correct way to emit to a specific user is like this:
socket.broadcast.to().emit();

Related

Braintree Node.js cannot get transaction.sale to work

I am building a reactjs app that among others will include Braintree Dropin UI integration. So far, I have managed to make the UI show up and send a payload to the back end. However, I cannot get the gateway.transaction.sale() part to work. Here is my code's relevant parts:
When the user clicks the pay button, this is fired:
instance.requestPaymentMethod().then(function (payload) {
console.log(payload);
completePayment(amount, payload.nonce, userId, sessionId).then((result) => {
console.log( result );
});
}).catch(function (err) {
alert(err.message);
});
And this is the code that should handle the transaction:
return gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
customFields: {
session_id: sessionId,
user_id: userId
},
options: {
submitForSettlement: true
}
}).then(function (result) {
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
}).catch(( error ) => {
alert(error);
});
Every time this function is fired, I get this error from catch:
TypeError: can't assign to property "success" on :not an object
Can anyone point me in the right direction?
Please note that I am not very familiar with react, node etc so my code may not be the best thing around...
Check these points:
make sure you assigned your environment to the sandbox (braintree.Environment.Sandbox);
double check (merchantId, publicKey, and privateKey).

Trouble with React Native Push Notification

I'm currently working on a Android mobile App.
It's a kitchen recipes app. The app will send notification to the user during the day.
In the settings of the app, the user can choose how many and at what time he will receive the notifications (11 am to 7 pm for example)
This is where the problem begins;
I use the react-native-push-notification library with the following code:
static LocalNotif(string)
{
PushNotification.localNotification({
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
title: "Vérifier vos produit", // (optional)
message: string, // (required)
largeIcon: "ic_launcher",
smallIcon: "ic_notification",
});
}
Next, I use the react-native-background-fetch to send a notification, even if the app is not running
static async backFetch(delay_to_next_notif)
{
BackgroundFetch.configure({
minimumFetchInterval: 3600
}, async (taskId) => {
// This is the fetch-event callback.
console.log("[BackgroundFetch] taskId: ", taskId);
// Use a switch statement to route task-handling.
switch (taskId) {
case 'com.foo.customtask':
this.LocalNotif("test")
break;
default:
console.log("Default fetch task");
}
// Finish, providing received taskId.
BackgroundFetch.finish(taskId);
});
// Step 2: Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
taskId: "com.foo.customtask",
forceAlarmManager: true,
delay: delay_to_next_notif// <-- milliseconds
});
}
The use of react-native-background-fetch is very strange. Sometime I never receive the notification.
Is it possible to use a push notification library and create a routine so that the user receives notifications at specific times during the day, even if the app is not running?
You can use Pushnptification.configure method and set your state if your app is in forground or background something like this
async componentDidMount() {
await this.requestUserPermission();
PushNotification.configure({
onNotification: (notification) => {
console.log('NOTIFICATION', notification);
if (notification.foreground === false) {
console.log('app is in background')
}
this.setState({
msg: notification.message.body
? notification.message.body
: notification.message,
forground: notification.foreground,
});
},
});
}
and in your return u can do something like this
{this.state.forground === true
? showMessage({
message: this.state.msg,
backgroundColor: '#1191cf',
type: 'default',
duration: 10000,
icon: 'success',
onPress: () => {
console.log('app is in forground')
},
})
: null}

How to post a button in postMessageToChannel to the slack channel and call a function on click of button?

I want to send a button in bot.postMessageToChannel() and want to call a function(handleMessage) on Click of that button.
//start handler
bot.on('start', () => {
const params = {
icon_emoji: ':information_source:'
}
//here i want to post a button to a channel.
bot.postMessageToChannel(
'ABC', //channel name
'*Welcome to AB*...',
params
)
})
function i want to call,
handleMessage = (message) => {
console.log("hello")
}
I have tried the slack API.
Message Buttons with Node.js but it is from the slash commands.
interactive message button it is just giving me similar JSON data.
I wanted to confirm what you were looking for before I answered. I did something similar recently - where I would return a button off of a command, mainly so that when the user clicked on the button I would have a trigger_id that I could use to send a modal form for them to provide more info. An example of how I handled this:
First go to the Event Subscriptions section of your app settings page, and enable it. Provide the url that will listen for said events, then you need to select the events that your bot will be listening for. I subscribed to app_mention ( which will fire when your bot is #), and message.channels, which will fire on every message sent to the channel your bot is in.
Once you have done that you can subscribe to events... (by using the slack SDK https://slack.dev/node-slack-sdk/)
slackEvents.on('message', (event, body) => {
// do something here
console.log(`Received a message event: user ${event.user} in channel ${event.channel} says ${event.text}`);
});
In my case, once I received that message (I parse through the text to handle multiple commands) I would then use blocks to create a message with a button and send it back...
Payload:
channel: context.channelId,
text: "",
blocks: JSON.stringify([
{
type: "section",
text: {
type: "mrkdwn",
text: "So, you say you want to create a new task?\n*Great!*\nI just need your permission first, in order to initiate this action.\nPlease click the button below to launch this process, or cancel if you have changed your mind"
}
},
{
type: "actions",
block_id: "processAddTask",
elements: [
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Process"
},
style: "primary",
value: "1"
},
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Cancel"
},
style: "danger",
value: "0"
}
]
}
])
Then send that payload back to channel...
const response = await web.chat.postMessage(responseMessage);
Once all this was done the user would be presented with a couple of buttons, and when they clicked on the "go" button it will fire another event that you can catch:
slackInteractions.action({ callbackId: 'addTaskRequest' }, (payload, respond) => {
console.log('payload', payload);
let triggerId = payload.trigger_id;
let view = payloads.addTaskModal({ triggerId });
(async () => {
try {
let result = await slackClient.callAPIMethod("views.open", view);
respond("");
} catch (error) {
if (error.code === ErrorCode.PlatformError) {
respond(error.data);
} else {
respond('Well, that was unexpected.');
}
}
})();
});

SailsJs websocket with a custom route instead of blueprint?

I am following the official Sails docs. Would like to implement the most basic socket functionality, i.e. client connects to a socket and when server notifies it about a response, executes a script.
The problem is that the socket requests are http and I am getting badRequest.
What's the right way to register a socket route in Sails?
My client code:
io.socket.on('hello', function (data) {
console.log('Socket `' + data.id + '` joined the party!')
})
io.socket.get('/sayhello', function gotResponse(data, jwRes) {
console.log('Server responded with status code ' + jwRes.statusCode + ' and data: ', data);
});
The controller:
module.exports = {
exits: {
badRequest: {
responseType: 'badRequest',
description: 'The provided data is invalid.',
},
},
fn: async function (req, res) {
if (!req.isSocket) {
return res.badRequest();
}
sails.sockets.join(req, 'funSockets');
sails.sockets.broadcast('funSockets', 'hello', {howdy: 'hi there!'}, req);
return res.json({
anyData: 'we want to send back'
});
}
}
The route:
'GET /sayhello': { action: 'project/api/app-socket' },
In your routes.js file you have:
'GET /sayhello': { action: 'project/api/app-socket' },
Add to this isSocket: true. So make it:
'GET /sayhello': { action: 'project/api/app-socket', isSocket: true },
How I learned this?
The convention for subscribe endpoints is to use an action prefixed with "subscribe", so when I generated an action with this command and this prefix:
sails generate action task/subscribe-to-task
Then it gave me this hint in the terminal output:
Successfully generated:
•- api/controllers/task/subscribe-to-task.js
A few reminders:
(1) For most projects, you'll need to manually configure an explicit route
in your `config/routes.js` file; e.g.
'GET /api/v1/task/subscribe-to-task': { action: 'task/subscribe-to-task', isSocket: true },
That's how I learned that we needed to add isSocket: true.

Using Pusher with SimpleWebRTC

I've come across the SimpleWebRTC package. Trying to get it to work, but can't seem to get the remote stream coming through. I'm also using Pusher for signalling, rather than the default that comes with SimpleWebRTC.
I've set up my own connection:
var myConnection = {
pusher: new Pusher('mypusherkey', { cluster: 'ap1' } ),
channel: null,
on: function (event, callback) {
this.pusher.bind (event, callback);
},
emit: function () {
if (arguments.length == 1) {
if (arguments[0] === "join") {
this.channel = this.pusher.subscribe(arguments[1]);
}
}
else
this.channel.trigger(arguments);
},
getSessionId: function() {
return this.pusher.connection.socket_id;
},
disconnect: function() {
this.pusher.disconnect();
}
};
Then I have the SimpleWebRTC initialisation:
var webrtc = new SimpleWebRTC({
// the id/element dom element that will hold "our" video
localVideoEl: 'localVideo',
// the id/element dom element that will hold remote videos
remoteVideosEl: 'remotesVideos',
// immediately ask for camera access
autoRequestMedia: true,
debug: true,
connection: myConnection
});
// we have to wait until it's ready
webrtc.on('readyToCall', function () {
console.log('ready to join');
// you can name it anything
webrtc.joinRoom('test-video-chat');
});
Doing a simple test between 2 PCs, it's not setting up the remote stream. In the dev console apart from the intitial event hook ups, I'm not seeing any other activity happening, especially SimpleWebRTC "readyToCall" not firing.
you probably need to emit a 'connect' signal from your socket adapter to trigger this code

Categories