Receiving Twilio 31201 error, despite having well-formed token - javascript

I'm using the following code from the Twilio Programmable Video Javascript Quickstart Guide, trying to Initialize the SDK with an access token:
https://www.twilio.com/docs/api/video/guide/identity
// Create an AccessManager to manage our Access Token
var accessManager = new Twilio.AccessManager('$TWILIO_ACCESS_TOKEN');
// Create a Conversations Client and connect to Twilio's backend
conversationsClient = new Twilio.Conversations.Client(accessManager);
conversationsClient.listen().then(function() {
console.log('Connected to Twilio!');
}, function (error) {
console.log('Could not connect to Twilio: ' + error.message);
});
But before even hitting the "could not connect to Twilio" error message designed into the above code, I get the following console error:
twilio-conversations.min.js:91 Client ERROR r {_errorData: Object, name: "LISTEN_FAILED", message: "Gateway responded with: 31201 Unknown authentication error"}
I'm testing this on an https-enabled development server, via ngrok.io. I've followed the code in the tutorial (link above) carefully. Does anyone understand what causes this cryptic 31201 error?

Related

Paho MQTT JS client loses connection to Mosquitto broker when I publish or receive message (error AMQJS0005E)

Bottom line up front: The Paho MQTT client sucessfully connects to my Mosquitto broker, but immediately disconnects when I try to publish a message or when it receives a message from a topic it's subscribed to. I've tried changing Mosquitto's listening port and authentication settings, and using two different versions of Paho MQTT, and I still have the same problem.
Now let's get into detail.
Intro: I'm making a dashboard for some facial recognition devices that communicate through MQTT. I set up a Mosquitto broker and I've had no problems connecting to it and communicating with the devices using the Paho MQTT client for Python (I made a kind of server to sync the device's info to a database). Now I'm making the web interface, so I added a WebSockets listener to my mosquitto.conf and wrote a script using the Paho MQTT library for Javascript to connect to it, subscribe to topic sgdrf/out, send a simple JSON message to topic sgdrf/in to get the list of online devices, and process the response of the Python server once it arrives.
Problem and attempted solutions: I ran the Django server, loaded the web page and opened the JS console to find that the MQTT client successfully connected to the broker but immediately disconnected when it tried to publish the message to topic sgdrf/in. Here's each line of console output with their explanations:
The message produced by the onSuccess function, which indicates that the client successfully connected to the Mosquitto broker:
Conexión exitosa al broker MQTT.
In the onConnected function, I added console.log(uri) to see the URI used by the client to connect to the broker. I got:
ws://localhost:61613/
After printing uri to console, I made the client subscribe to sgdrf/out and then print 'subscribed' to console:
subscribed
Then I call get_online_devices(mqtt_client), a function which creates a simple JSON string and publishes it to the topic sgdrf/in. But first, it prints the strign to the console so that I can check it (just in case):
{"operator":"GetOnlineDevices","messageId":96792535859850080000,"info":{}}
Then, when the publish method is actually executed, is when I get this error (captured by the onConnectionLost function):
Pérdida de conexión con el broker MQTT: AMQJS0005E Internal error. Error Message: message is not defined, Stack trace: No Error Stack Available (código: 5)
I checked the Mosquitto log file and it only says when a new client was connected and then when it was disconnected because of a socket error (each time for every page reload). Tail of /var/log/mosquitto/mosquitto.log:
1614796149: New connection from 127.0.0.1 on port 61612.
1614796149: New client connected from 127.0.0.1 as mqttx_53195902 (p2, c1, k60, u'admin').
1614796182: Socket error on client sgdrf_dashboard_8499, disconnecting.
1614796325: New client connected from ::ffff:127.0.0.1 as sgdrf_dashboard_1597 (p2, c1, k60, u'admin').
1614796325: Socket error on client sgdrf_dashboard_1597, disconnecting.
1614796336: New client connected from ::ffff:127.0.0.1 as sgdrf_dashboard_6565 (p2, c1, k60, u'admin').
1614796336: Socket error on client sgdrf_dashboard_6565, disconnecting.
1614796931: New client connected from ::ffff:127.0.0.1 as sgdrf_dashboard_9773 (p2, c1, k60, u'admin').
1614796931: Socket error on client sgdrf_dashboard_9773, disconnecting.
1614797168: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
I tried changing the listening port in mosquitto.conf, and enabling and disabling authentication, but it changes nothing. And obviously I've had to restart Mosquito every time I changed the config file. I don't think the problem is Mosquitto.
I have the same problem whether I use Paho MQTT version 1.1.0 or 1.0.3.
As an experiment, I commented out the call to get_online_devices in my Javascript so that it doesn't try to publish anything, reloaded the page and there was no error, as expected. Then, I used MQTTX to send a JSON message to the sgdrf/out topic to which the MQTT JS client is subscribed to, and it immediately disconnected with the same error message.
Code: At the bottom of the page (index.html) I have the following code (the original code has Django template tags to fill in some values, so this is the actual code received by the browser):
<!-- Paho MQTT -->
<script src="/static/js/paho-mqtt-min.js"></script>
<!-- Scripts -->
<script src="/static/js/dashboard.js"></script>
<script>
function get_online_devices(mqtt_client) {
cmd = {
operator: "GetOnlineDevices",
messageId: generate_random_number_n_exp(20),
info: {}
};
payload_string = JSON.stringify(cmd);
console.log(payload_string)
mqtt_client.publish("sgdrf/in", payload_string);
}
function add_device_to_list(device) {
// Omitted for brevity. It's not being used yet.
}
let mqtt_client = make_mqtt_client("localhost", 61613);
let connection_options = make_connection_options(
"admin",
"CENSORED_PASSWORD"
);
mqtt_client.onConnected = function(reconnect, uri) {
console.log(uri)
mqtt_client.subscribe("sgdrf/out");
console.log('subscribed');
get_online_devices(mqtt_client);
};
mqtt_client.onConnectionLost = mqtt_client_on_connection_lost;
mqtt_client.onMessageDelivered = mqtt_client_on_message_delivered;
mqtt_client.onMessageArrived = function (msg) {
// Omitted for brevity. Checks if the payload is a
// JSON object with the right data and calls
// add_device_to_list for each item of a list in it.
};
$(document).ready(function() {
mqtt_client.connect(connection_options);
$("#reload-device-list-btn").click(function() {
get_online_devices(mqtt_client);
});
});
</script>
The dashboard.js files mentioned above just has some functions that I think will be useful for other pages, so I separated them to a file:
// dashboard.js
function generate_random_number_n_exp(n) {
return parseInt(Math.random() * Math.pow(10, n), 10)
}
function make_mqtt_client(host, port) {
let client_id = "sgdrf_dashboard_" + generate_random_number_n_exp(4);
return new Paho.Client(host, port, '/', client_id);
}
function make_connection_options(user, password) {
let connection_options = {
userName: user,
password: password,
onSuccess: mqtt_client_on_success,
onFailure: mqtt_client_on_failure,
};
return connection_options;
}
function mqtt_client_on_success() {
console.log('Conexión exitosa al broker MQTT.');
}
function mqtt_client_on_failure(error) {
console.log(
'Fallo de conexión con el broker MQTT: ' + error.errorMessage
+ ' (código: ' + error.errorCode + ')'
);
}
function mqtt_client_on_connection_lost (error) {
console.log('Pérdida de conexión con el broker MQTT: ' + error.errorMessage
+ ' (código: ' + error.errorCode + ')'
);
}
function mqtt_client_on_message_delivered(msg) {
let topic = message.destinationName;
let payload = message.payloadString;
console.log("Mensaje enviado a " + topic + ": " + payload);
}
function mqtt_client_on_message_arrived(msg) {
let topic = message.destinationName;
let payload = message.payloadString;
console.log("Mensaje recibido de " + topic + ": " + payload);
}
Here are the contents of my mosquitto.conf file:
per_listener_settings true
listener 61612
allow_anonymous false
password_file /home/s8a/Projects/sgdrf/config/pwdfile.txt
listener 61613
protocol websockets
allow_anonymous false
password_file /home/s8a/Projects/sgdrf/config/pwdfile.txt
It just sets up a TCP listener and a WebSockets listener, both disallow anonymous connections, and authenticate using a pwdfile. As I said before, I have enabled and disabled anonymous connections, and changed the port number to 9001 and back to 61613, and I still have the same error.
Conclusion: I don't know what to do and this project's deadline is next week.
I feel kinda stupid, because it was really a trivial typing mistake. The problem is that the onMessageDelivered and onMessageArrived functions have msg as argument, but I wrote messagein the function body for some reason. That's what the "message is not defined" error meant, message is literally not defined. Anyway I fixed that and now it sends and receives messages without problems.
...
More detailed story: What was not trivial is how I figured it out.
I decided to get my hands dirty and opened the non-minified version of paho-mqtt.js. I looked for "Invalid error" and found where the error constant is defined, and two places where it's used in a catch block. In both catch blocks I noticed that there was a ternary operator checking if (error.hasOwnProperty("stack") == "undefined") but the true and false clauses were inverted, which is why I was getting "No Error Stack Available".
So I inverted the clauses, and indeed I got a stack trace in the console (maybe I should file a bug report to the Paho dev team when I can). The stack trace had my mqtt_client_on_message_delivered function right at the top, so I read it again and suddenly everything made sense. Then I felt stupid for wasting an afternoon on this.

Sending 500 ("Server Error") response when visiting any url in Sails App

I am using Sails and Mysql to handle the database of my app. I recently clicked on a chrome autofill URL that took me to a 404'd page, since that url localhost:1337/companies was not active in this project.
Ever since I did that, my app returns
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
and
Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
any time I go to a url in my app. I tried cloning my app and relinking the database to no avail. I see this is a common issue people run into with sails, but none of the mentioned solutions were able to fix it for me.
Everything was working before I clicked that URL which makes me believe it may be a route issue, but the app still works, it will just fill up my terminal with the above errors.
Any help is greatly appreciated!
Edit: this is the custom API call I was working on in my controller.js when I started seeing the error:
winner: function (req, res) {
User.findOne({id: req.param('id')}).exec(function(err, user) {
if (err) {
return res.negotiate(err);
}
else {
var u = user;
u.totalwins++;
u.save();
sails.io.sockets.emit("chat", {verb:"score", data:{id: req.param('id'), name: user.name}});
}
});
}
Also receiving this error in my chrome-browser console:
:1337/user/quizzes Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Can't send mail with Cloud Functions for Firebase

I'm trying to send an email from a Cloud Function using the sendmail package.
It works when I host my "send function" locally. And I can deploy the function without problems to my Firebase project.
In the log at Firebase I can see this message:
Error: queryMx ESERVFAIL hotmail.com
at errnoException (dns.js:28:10)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:219:19)
I'm neither familiar with sending emails from servers or Cloud Functions for Firebase. My question is why I got this error and how I can make it work?
Here is an excerpt from my function:
sendmail({
from: body.name + ' ' + '<' + body.email + '>',
to: 'soerensmed#hotmail.com',
subject: 'Henvendelse via kontaktformular',
html: html,
}, function (err, reply) {
if (err) {
console.log(err && err.stack);
response.status(500).end()
}
else {
console.log(reply)
response.status(200).end()
}
});
I'm developing a website where people can contact me through a contact form. The goal is to receive an email with the message... If this approach isn't possible I'm open for suggestions on how I can set this contact-email-thing up using Angular and Firebase.
It will not work with cloud function with free spark account. You should upgrade as it is clearly defined in pricing section in network box. https://firebase.google.com/pricing/

How to know if a connection error occurred when using thrift from a javascript client?

I'm running the following thrift javascript client code. If the server is down, I don't get any error in the callback - just console log message.
How do I know if there're connection issues if the callback isn't invoked?
Javascript thrift client code:
var transport = new Thrift.Transport("/api/thrift/");
var protocol = new Thrift.Protocol(transport);
var client = new ApiClient(protocol);
client.doSomething(function (result) {
// Never invoked if the server is down.
});
Console log message:
POST http://localhost:81/api/thrift/ net::ERR_CONNECTION_REFUSED

Websocket-Rails Channel 'Error during WebSocket Handshake'

I'm trying to use websocket-rails to broadcast live routes as they come in to my site. However, I'm unable to get any messages to be published. I've read all of the help I could find, and I can't seem to get a solution.
Here is what the javascript I have in application.html.erb:
var route_name = window.location.pathname + window.location.search;
$.post("/realtimeroutes",
{ data: { route_name: route_name} },
function(response) {
}
);
This data is handed off to a rails controller method realtime_routes which looks like this:
def realtime_routes
puts '*** The Route Data is: ' + params[:data][:route_name]);
new_route = RouteCatcher.new(route_name: params[:data][:route_name]
if new_route.save
route = {route_name: params[:data][:route_name]}
puts '*** Right before the Message is sent ***'
WebsocketRails[:new_route].trigger('new', route)
puts '*** Right After the Message is sent ***'
render nothing: true
else
render nothing: true
end
end
To this point everything is fine. updates are happening in the DB and both the before and after messages are printing to the console, but there is no Websocket Message fired.
Next I have this javascript listening in realtime.html.erb:
var dispatcher = new WebSocketRails(window.location.host + '/websocket');
var channel = dispatcher.subscribe('new_route');
channel.bind('new', function(route) {
console.log('********** Inside Bind Event');
console.log('********** a new route '+ route.route_name +' arrived!');
});
Nothing is ever being received on the bind event and when I look in the Console on Chrome, I get:
'Uncaught ReferenceError: WebSocketRails is not defined'
So I'm absolutely stuck here as I've followed every bit of documentation I can find and really have no idea where to go. Any help with this is greatly appreciated.
UPDATE: That was an initialization error because the WebSocketRails was being rendered before the rest of the application js.
However, now I am getting the error:
WebSocket connection to 'ws://localhost:3000/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301
After reading further about other people with the same error, it seems prudent to mention that I am using Puma on AWS elasticbeanstalk with SSL in production.

Categories

Resources