Add MUC library to be used for conversing with helpers

Thu, 18 Mar 2010 15:53:39 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Thu, 18 Mar 2010 15:53:39 +0000
changeset 19
41a3c9d41e6a
parent 18
9e4230bb66e4
child 20
bd1d350ab61c

Add MUC library to be used for conversing with helpers

js/xmpp_muc.js file | annotate | diff | comparison | revisions
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/js/xmpp_muc.js	Thu Mar 18 15:53:39 2010 +0000
@@ -0,0 +1,94 @@
+// Wraps a function so that its 'this' is always 'context' when called
+var recontext = function (context, f) { return function () { return f.apply(context, arguments); }; };
+
+var MUC = function (conn, callbacks)
+{
+	/* Set our properties */
+	this.conn = conn;
+	this.callbacks = callbacks;
+
+	this.occupants = {};
+
+	/* Initialize stanza handlers */
+	conn.addHandler(recontext(this, this.handle_join), null, "presence", null, null, null);
+	conn.addHandler(recontext(this, this.handle_error), null, "presence", "error", null, null);
+
+	/* Return newly-created object */
+	return this;
+}
+
+MUC.prototype =
+{
+	/** General methods */
+
+	join: function (jid, nick, status_text)
+	{
+		this.jid = jid;
+		this.nick = nick;
+		var pres = $pres({to: jid+'/'+nick});
+		if(status)
+			pres.c("status").t(status);
+		return this.send_stanza(pres);
+	},
+
+	part: function (status_text)
+	{
+		var pres = $pres({to: this.jid+'/'+this.nick, type: "unavailable"});
+		if(status)
+			pres.c("status").t(status);
+		return this.send_stanza(pres);
+	},
+
+	send_message: function (message)
+	{
+		return this.send_stanza($msg({to: this.jid, type: "groupchat"})
+			.c("body").t(message||""));
+	},
+
+	send_stanza: function (stanza)
+	{
+		return this.conn.send(stanza.tree());
+	},
+
+	/** Incoming stanza handlers */
+
+	handle_join: function (stanza)
+	{
+		var nick = Strophe.getResourceFromJid(stanza.getAttribute("from"));
+		if(stanza.getAttribute("type") != "unavailable" && stanza.getAttribute("type") != "error"
+		     && Strophe.getBareJidFromJid(stanza.getAttribute("from")) == this.jid)
+			if(!this.occupants[nick])
+			{
+				var text = stanza.getElementsByTagName("status")[0];
+				if(text) text = Strophe.getText(text);
+				this.occupants[nick] = {};
+				if(this.callbacks.joined)
+					this.callbacks.joined(stanza, this, nick, text);
+				if(this.status_handler)
+				{
+					this.status_handler(stanza);
+				}
+			}
+		return true;
+	},
+
+	handle_error: function (stanza)
+	{
+		if(this.callbacks.error
+			&& Strophe.getBareJidFromJid(stanza.getAttribute("from")) == this.jid)
+		{
+			var e = stanza.getElementsByTagName("error");
+			if(e.length > 0)
+			{
+				var err = null;
+				Strophe.forEachChild(e[0], null, function (child)
+					{
+						if(child.getAttribute("xmlns") == "urn:ietf:params:xml:ns:xmpp-stanzas")
+							err = child.nodeName;
+					});
+				this.callbacks.error(stanza, this, err);
+			}
+		}
+		return true;
+	}
+};

mercurial