WebRTC setLocalDescription from answer resets signalingState - reactjs

I am attempting a simple example of two users connected with webrtc using a data channel. The problem I am having is after the offer step. The second client that joins my socket.io room, I have send an offer and sets its local description.
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer)
//send offer to signal server to forward to peer
socket.emit("webrtc_offer", {
roomId: roomId,
sdp: peerConnection.localDescription,
});
Then when I receive the offer I try this...
if (!offerSender) {
await peerConnection.setRemoteDescription(offer);
const answer = await peerConnection.createAnswer();
//This sets the signalingState to stable instead of have-local-pranswer
await peerConnection.setLocalDescription(answer);
console.log("sending answer to peer");
socket.emit("webrtc_answer", {
roomId: roomId,
sdp: peerConnection.localDescription,
});
}
Once I try to set the local description from the answer I create, my signalState is reset to Stable instead of have-local-pranswer. Could someone explain why that is? This then breaks the next step of trying to respond to the answer to finish the connection.

Related

redux dispatcher doesnt set some specific messages from socket (signalR)

i open the connection in a parent component above all and when a message comes i set it via redux and use it in another component. It's all good till messages come together(like glued) as shown in photo. when messages are received together redux sets one of two received messages. how do i overpass this issue that redux could handle each of socket's messages.
await hubConnection.start()
.then(()=>{
hubConnection?.on("ReceiveOrderEvents", (messageStreamItem: any) => {
console.log(messageStreamItem,'messageStreamItem')
dispatch(orderUpdateSocket(messageStreamItem));
});
})
after couple of days figuring out what the origin of problem was, i came up with an idea this solution:
since socket might send multiple messages very fast and in a very short time, redux might not handle it very well. messages from socket could be stored in an array and via forEach you could dispatch every one of them inside a setTimeOut function to proceed with other things you are about to do.
await hubConnection.start()
.then(()=>{
hubConnection?.on("ReceiveOrderEvents", (messageStreamItem: any) => {
let msg=[];
msg.push(messageStreamItem);
setTimeOut(()=>{
msg.forEach((message:any)=>dispatch(setter(messageStreamItem)));
msg = []
},[50])
});
})

How do I manage voice connections from multiple bots in one code?

My code manages multiple and different Discord bots, and to check what bot has to perform a certain action there's an algorithm that looks just like the following:
function getHandlerByClient(client: Discord.Client): (typeof MusicHandler) {
if (Utils.checkClientByToken(client, Constants.MUSIC1_TOKEN)) return MusicHandler1;
else if (Utils.checkClientByToken(client, Constants.MUSIC2_TOKEN)) return MusicHandler2;
else if (Utils.checkClientByToken(client, Constants.MUSIC3_TOKEN)) return MusicHandler3;
return MusicHandler;
}
On previous Discord.js versions I could just execute something like:
let joinEvent = channel.join();
and it would work just fine, the correct bot instance would execute that code. Now everything's changed and I have to run:
let connection = DiscordVoice.joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator
});
and it doesn't even work as it did before: if I play something on bot#1 and then without having it stopped play something else on bot#2, bot#2 doesn't join the channel and plays everything in bot#1. So whenever I run play on any of the bots, all the others won't join channels until the first one called quits. How can I solve this?
I'm not sure if after 3 months my answer will help, but maybe someone will also face this problem.
I struggled all day with the same problem, and to my great fortune I found the answer in the official discord server discord.js.
solution
I simply add client.user.id as group identificator and use voiceAdapterCreator from a certain client that i need like this:
/* attachedBot.client - the bot client that you want to connect to voice channel */
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channelId,
guildId: interaction.guild.id,
adapterCreator: (await (await attachedBot.client.guilds.fetch()).find(g => g.id === interaction.guild.id).fetch()).voiceAdapterCreator,
group: attachedBot.client.user.id
});
And this works fine for me

Discord.js move messages in a different Channel

I'm trying to make the t!suggestion command work on different Servers. My problem is that i used the Channel ID in the following Code, which is obviously not working on a second Server. So my thought was to exchange the Channel ID and use the Channel Name. Unfortunatley i have no idea how to do that. And therefore are my question. Is it possible to just change the Code and use the Channel Name instead of the Channel ID and would that work?
bot.on("message", async (message) => {
if (message.content.startsWith("t!suggestion")) {
var str = message.content.slice(" t!suggestion".length);
const channelToSendId = "8786607442820137466";
const embed = new Discord.MessageEmbed()
.setThumbnail("Picture")
.setAuthor("TestBot", "small picture")
.setTitle("Suggestion")
.setColor("#151515")
.addFields({ name: "Person, that suggested somenthing:", value: `<#!${message.author.id}>` }, { name: "suggestion:", value: `${str}` }, { name: "Channel:", value: `${message.channel}` })
.setTimestamp();
await bot.channels.cache
.get(channelToSendId)
.send(embed)
.then((embedMessage) => {
embedMessage.react("✅");
embedMessage.react("❌");
});
message.delete();
}
});
Using the find method will work.
Change this
bot.channels.cache.get(channelToSendId)
To this
bot.channels.cache.find(c => c.name === 'suggestions')
The get method always finds by id (that’s how discord.js sets it), but you can put a condition in find. Note that it is a function. Another problem is that this will still only work on one channel, even if the command is run in a different guild. To fix that, you should only check the current guild's channels.
message.guild.channels.cache.find(c => c.name === 'suggestions')
This will find the channel with the name suggestions (we don’t put the # in the code) and send the message there. Keep in mind you may receive an error if the channel is not found.

Stripe Create Payment Intents Promise Never Resolves

I signed up for a Stripe account and followed some simple steps to get up and running with Node. I just installed the package and tested a payment Intents with my test key:
const Stripe = require('stripe');
const handleStripe = async () => {
const stripe = Stripe(testKeyString);
console.log(“we make it here”);
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
payment_method_types: ['card'],
receipt_email: 'jenny.rosen#example.com',
});
//we never make it here
console.log(paymentIntent);
}
catch(err){
//we never make it here either
console.log(err);
}
}
The console logs “we make it here”, but nothing else. The promise is never resolved.
I suspect that this might be a bug with the stripe npm package. Anybody have any thoughts on why the promise is never returned?
EDIT: sorry, I wasted everyone’s time here. I was following the docs QuickStart where it said “install a client library” and I assumed it was for the front end. So a very silly mistake on my part thinking that it was a good idea to make a payment intent from the front end with a secret key. Just getting going with the Stripe API and I’m off to a bad start. Thanks for your comments and answer
Thanks
What happens if you run it without the try/catch? Also what do you get if you try https://status.stripe.com/reachability from that server - are you sure you can reach Stripe's servers?

How do I send user specific data with socket.io and laravel?

I am not sure how to word this question right, but here I go. I have laravel, angular, node w/socket.io and I am also using JWT for authentication. My end goal is to be able to send real time update notifications to specific users. For the life of me, I cannot seem to get how the workflow would be.
My initial though was to send the jwt within the handshake and then use then in node to do http requests to get data, and then return said data. In another words, when a specific event is fired, node will already have the token, send request to laravel for specific information.
Can someone please explain to me how sending user specific data via socket.io in this architecture?
I found this great article : https://www.ukietech.com/blog/programming/step-by-step-instruction-of-setting-up-real-time-secure-broadcasting-with-laravel-5-1-socket-io-and-redis/
This set me on the right track.
First I need to pass in my JWT into the socket:
var socket = io('http://192.168.10.10:3000', {query: "Authorization="+$rootScope.$storage.satellizer_token});
Next I actually verify the token.. again. I know this may be overkill, but I want to know that what hits the socket is legit.
io.use(function(socket, next){
if (socket.handshake.query.Authorization) {
var config = {
url:'http://192.168.10.10/api/auth',
headers:{
Authorization:'Bearer '+socket.handshake.query.Authorization
}
};
request.get(config,function(error,response,body){
socket.userId = JSON.parse(body).id;
next();
});
}
// call next() with an Error if you need to reject the connection.
next(new Error('Authentication error'));
});
The request in this block of code returns a user object based on the authenticated token. Refer to JWTAuth for more.
Then on connection I will assign the user to a unique channel.
io.on('connection',function(socket){
socket.join('userNotifications.'+socket.userId);
console.log('user joined room: userNotifications.'+socket.userId);
});
Then broadcast the event:
notifications.on('pmessage', function(subscribed, channel, message) {
var m = JSON.parse(message);
io.emit(channel+":"+m.event, message);
});
Back on the client side I listen for the channel. the var user is the user id.
socket.on('userNotifications.'+ user+':App\\Events\\notifications', function(message){
console.log(message);
});

Resources