Django + Strophe + ejabberd - troubles with attach and groupchat - django

I try to use strophe + ejabberd to make something like webchat.
What i've done already:
when I login to website, i also authenticate to ejabberd (to achieve RID and SID),
after login is finished, i attach RID and SID i got from context processor,
connection status seems to be: connection established, logs:
.
POST: <body rid='406266360' xmlns='http://jabber.org/protocol/httpbind' sid='9c66aa19123e96dc2925c24d4f985d458763eb67'><presence xmlns='jabber:client'><priority>-1</priority></presence><presence to='localhost/m' xmlns='jabber:client'><x xmlns='http://jabber.org/protocol/muc'/></presence></body>
RESP: <body xmlns='http://jabber.org/protocol/httpbind'><success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/></body>
After that, connection hangs on:
POST: <body rid='406266361' xmlns='http://jabber.org/protocol/httpbind' sid='9c66aa19123e96dc2925c24d4f985d458763eb67'/>
When i try to send a message now (while its hanged):
POST: <body rid='406266362' xmlns='http://jabber.org/protocol/httpbind' sid='175e45333109f74c36f9dffbe4e3cc6cffc80df4'><message to='localhost' type='groupchat' xmlns='jabber:client'><body>yrdy</body></message></body>
Im getting:
RESP: <body type='terminate' condition='remote-stream-error' xmlns='http://jabber.org/protocol/httpbind' xmlns:stream='http://etherx.jabber.org/streams'><stream:error><xml-not-well-formed xmlns='urn:ietf:params:xml:ns:xmpp-streams'/></stream:error></body>
Whats wrong? Strange thing is that after some seconds request is aborted, and next request hangs again. When i try to send message then, there are no errors but response is:
RESP: <body xmlns='http://jabber.org/protocol/httpbind'/>
With no errors (connection is still connected and authenticated, but message doesnt seem to be delivered).
Code I use to send message:
var body = $('#input_text').val(); | // make sure this presence is for the right room
var msg_body = { | if (room === Groupie.room) {
to: Chat.room, | var nick = Strophe.getResourceFromJid(from);
type: 'groupchat' |
} | if ($(presence).attr('type') === 'error' &&
var msg = $msg(msg_body).c('body').t(body); | !Groupie.joined) {
| // error joining room; reset app
Chat.connection.send(msg);

You can use Strophe.js to attach like so:
Chat.connection = new Strophe.Connection(Chat.BOSH_SERVICE_URL);
Chat.connection.attach(jid, sid, rid, onConnectHandler);
onConnectHandler is then called once you've attached successfully. From then one, you don't have to worry about the SID and RID again (until page reload).
Also, are you aware of the MUC strophe plugin?
If you want some example code to use/study, I wrote something similar to what you're doing for Plone, called collective.xmpp.chat
The javascript is reusable separately: converse.js

Related

How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?

I have a websocket in one of my http-mock server files initialised as follows:
var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});
and later in the file I have the following happen on connection:
socketServer.on('connection', function(ws) {
ws.on('close', function(message) {
clearInterval(sendResults);
});
ws.on('message', function(message) {
handleClientMessage(ws, message);
});
sendResults = setInterval(function() {
ws.send(JSON.stringify(getResultsFromEntries()));
}, resultInterval);
});
However, whenever I edit any of the server files I get the following error:
File changed: "mocks/entry.js"
Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE 0.0.0.0:13434
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at Server._listen2 (net.js:1250:14)
at listen (net.js:1286:10)
at net.js:1395:9
at nextTickCallbackWith3Args (node.js:453:9)
at process._tickCallback (node.js:359:17)
I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file. Any ideas?
I ended up setting a new WebSocketServer as a property of process (which persists over the server getting restarted) then at the top of the file I close the previous WebSocketServer (if there was one):
if (process["updateSocketServer"]) {
process["updateSocketServer"].close();
process["updateSocketServer"] = undefined;
}
Then setup a new WebSocketServer:
process["updateSocketServer"] = new WebSocketServer({port: 13434, path: "/update"});
Then I did the following on connection:
process["updateSocketServer"].on('connection', function(ws) {
// Connection code.
});
Should you be closing/terminating the connection on close?

QWebEngine: handling get and post requests when a runJavaScript is performed

I am looking for possibility of handling get and post requests made by running a java-script code after a website is loaded. Here is the description: a url could be loaded via QWebEnginePage::load and the page contains some buttons with javescript events bind to them. buttons do some get and post requests from internet. Is there anyway that I could signal my classes when the get and post requests are performed by that javascript events. If it is impossible with QWebEngine What are the other options in Qt to do job. I am looking for some options that would not be absolute in the future since it is part of long-term project.
Thanks
You can use QWebChannel that should work in your case.
CPP file
QWebChannel* webChannel = new QWebChannel();
webChannel->registerObject("foo", this);
webview->page()->setWebChannel(webChannel);
in HTML file
<script type="text/javascript" src="qrc:/Map/qwebchannel.js"></script>
<script type="text/javascript">
new QWebChannel(qt.webChannelTransport, function(channel) {
// all published objects are available in channel.objects under
// the identifier set in their attached WebChannel.id property
var foo = channel.objects.foo;
// access a property
alert(foo.hello);
// connect to a signal
foo.someSignal.connect(function(message) {
alert("Got signal: " + message);
});
// invoke a method, and receive the return value asynchronously
foo.someMethod("bar", function(ret) {
alert("Got return value: " + ret);
});
});
</script>

Facebook graph API fail to load resource bad request 400

I have the following code on my controller.js and works when I request from Facebook Graph 2.4
request.open("GET","https://graph.facebook.com/v2.4/katyperry/posts?"+access_token,true);
However this only returns few fields: message, story, created_time, and id.
I need some additional more fields: message, picture, likes, created_time, link, type, comments and object_id.
So I tried the following:
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}"+access_token,true);
The last one sent me the error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
I tested both options the request on the Graph API Explorer and it worked properly. How can I get those extra fields? what am I missing?
I am adding the precedent code to show how access_token is builded:
var appID ="138429819833219";
var appSecret ="dada0a4d7f7717b0d37fd637d9e1522a";
var accessTokenRq = makeHttpRequest();
var httpString = 'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id='+appID+'&client_secret='+appSecret;
accessTokenRq.open("GET",httpString,true);
accessTokenRq.send(null);
var access_token;
accessTokenRq.onreadystatechange = function() {
if (accessTokenRq.readyState == 4) {
access_token = accessTokenRq.responseText;
//alert("Hat geklappt - Trabajó :)");
var request = makeHttpRequest();
// the following request works
request.open("GET","https://graph.facebook.com/v2.2/katyperry/posts?"+access_token,true);
// next one don't - I checked inspector and access_token contains: 138429819833219|CewVrYOd86ctJ0HTP2X0XAS9m4o
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}"+access_token,true);
What is contained in the access_token variable? The request
/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}
works in the Graph API Explorer, so I guess your access_token variable only contains the actual access token, and not the parameter key/value pair.
This
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}&access_token="+access_token,true);
should hopefully work then.
The error it was syntax, the right code as follow:
request.open("GET","https://graph.facebook.com/v2.4/katyperry/posts?limit=2&fields=message,picture,likes,created_time,link,type,comments,object_id&"+access_token,true);

How to retrieve request info by request id?

When I invite my friends I get back request_ids. After that I proceed those ids to get info about users invites have been sent to and create records in my database based on user's public profile info. But when I try to get request info by request id I get error message saying "Unsupported get request" nevertheless access token is fine.
// create data object to be sent to FB API
var data = new Object();
data.method = 'apprequests';
data.message = MESSAGE_TEXT;
data.display = 'iframe';
data.access_token = ACCESS_TOKEN;
data.show_error = 'Yes';
data.title = TITLE_TEXT;
// call FB API
FB.ui(data, function(aResponse)
{
var request_ids = '';
if (aResponse && aResponse.request_ids)
request_ids = aResponse.request_ids.join(',');
if (request_ids)
{
// send request_ids string to my server for further processing
}
});
Example of such broken request id: 1930910810837. Trying to get info for it like this:
https://graph.facebook.com/1930910810837?access_token=ACCESS_TOKEN
Please help me understand what is wrong. May it be issue on Facebook side, for example, Facebook returned broken id for some reason? Thank you!!!

How do I read a Django HTTPResponse in Flex?

I'm a complete Flex noob, so I apologize in advance if I'm missing something obvious.
I wrote a fairly simple file uploader in Flex, which calls my Django back-end via URLRequest (the FileReference object handles the upload). My upload works as intended and I have Django return a HTTPResponse object. As such, I'd like to read the contents of the HTTPResponse object.
Any thoughts?
something along the lines of
<mx:HTTPService id="myHTTPRequest"
url="{whatever your url request is}"
result="resultHandler(event)"
fault="faultHandler(event)"
showBusyCursor="true"
resultFormat="object">
then inside the resultHandler something like this
private function resultHandler (event : ResultEvent) : void {
var obj : Object = event.result;
//do something with returned object
}
Debug at the point of the resultHandler to see exaclty whats being returned, make sure its what you think should be getting returned.
By the time it gets to the client it's just a normal HTTP response so treat it like any other response
I am also new to flex and I ran in the same problem when doing an upload to a Java Rest backend, I solved it using the DateEvent on the FileReference. To get the response data use something like this.:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
var request:URLRequest = new URLRequest("yourUrl");
fileRef.upload(request, "fileData");
private function responseHandler(event:DataEvent):void {
var response:XML = new XML(event.data);
//Note the DataEvent: this is the event that holds the response.
//I sent back data as xml
}
Your response should always be a successful HTTP status code (200), if your backend sends status 500 codes it will not trigger the DateEvent. Server errors can still be caught with a HTTPStatusEvent, but then you don't have access to the response.
you can access the response like so in your onComplete event handler:
private function saveCompleteHandler(event:Event):void {
var loader:URLLoader = event.currentTarget as URLLoader;
trace("saveCompleteHandler - event returned:" + loader.data as String);
}
we do this this to get json fron a java web service.
you just need to use a URLLoader to load the URLRequest in the first place:
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler, 10000);
loader.addEventListener(IOErrorEvent.IO_ERROR, saveErrorHandler, 10000);
loader.addEventListener(Event.COMPLETE, saveCompleteHandler, 10000);
var request:URLRequest = new URLRequest("http:/whereverer");
request.method = URLRequestMethod.GET;
loader.load(request);