JabChapter 9

From WikiContent

Revision as of 07:51, 6 August 2009 by RacgeTcaze (Talk | contribs)
Jump to: navigation, search

nutrition education games for elementary school movie review spirit water the firm body sculpting system 3 review lonely russian woman counter strike 1.6 maps to download green hills school new jersey island marathon result tybee http ohio pug rescue new york blackout 1965 turnaround management firms tego calderon lyrics we dont love them hoes pelham school wimbledon colfax iowa history broadband optimizers central council for education and training in social work georgia gymnastics academy lawrenceville belltech business card designer pro 1.0 texas ford dealership louisiana representative districts is siberia part of russia new york state natural heritage trust buy email link name phentermine.html soma.orxc.com depot home improvement store fillmore poster ties amount of money spent on fast food pny 6800gt review texas renegade russian trilobites illinois historic site charlatte migennes france rock thr indiana jones music score system of a down legend of zelda song computer will not turn on links baby cat phat star way ohio reptile rescue national personnel records center military personnel records page kansas city rap georgia job university governers job bank texas algarve travel hawaii airline shiner high school index council of legal education victoria kansas city honda motorcycle education elementary resource school silent movie theater on fairfax american express money wire las vegas poker tournaments february printed sweatshirts gazebo designs wwe diva stacy keibler. razzle map iowa city entertainment walley fishing manitoba site indecent proposal video clip free gd55 mobile panasonic ringtone moms movies.com a perfect circle music video downloads amateur submitted movies auto nationwide watch.com marisa miller video free mobile panasonic ringtone movie schedule tinseltown sponges phylum popup blockers russian mature movies secretely music roger video zapp nude madonna dan post boots sitemap annie lennox ringtone framed photos movie clip heather graham link mass transit magazines coach replica amr ringtones free download english to german masterbate clit electric burr grinder pharmacy ethnic video sexual intercourse photos deer hunting igrice video microsoft open license site nostalgiques stickers russian movie download movie icon avatars anna ohura videos phentermine pharmacy biz wet nurses white water rafting wales uk playstation3 merman movies ritalin adderall concerta sitemap decadron preview torrent file mpeg4 movie converter asia movie trailer craigs list denver irish drink mix 2005 draft nhl media player movie trailors leonard maltin movie reviews apache mysql php windows installer hohner nik sharpener pro serial index link penneys radiator hose wu-tang clan woman naked lowden guitar serial numbers recurso humanos matthew perry drug addiction kill myself eminem puke video easy producer video aspiration book guest lex on blondes domain oxycontin lil wyte lyrics what is extacy drug pretty ricky video total wine naked photo post adam brody jimmy kimmel best way to lose weight magnum movie p.i infant blood pressure normal plastic license plate blanks allfreegay trackpad powerbook adobe photoshop 8 cs cracked interpreter memphis homes el nino red envolope irene hunt pictures pussy eating gallery free web design template pwl cracker download activation end process product software cell motorola phone razr ringtone showplace 16 coon rapids mn url in nevada pharmacy school sexy seamed stockings sample sex video and movie speculumpages archive video files free ringtones alltel audiovox nastyrat.com marmalade mr review lolita index alive blaine clip david drowned video pioneer press page aurora fox mall valley 2 best camera digital megapixel links eating a balanced diet adultactioncam.com cardizem cd anabolic steroids actos altace robert palmer simply irresistible music video girls messy cheerleader pacific assault no cd crack shemale domination lunchboxes live night rap saturday video karate kata video free ohiolottery rakuen movie 4 inuyasha smoothmag wholesale home tanning bed honda radiator skydiving video clip movie lobby card index environmental sampling supplies valassis ivp care pharmacy pure country movie quotes student housing chicago cubs index pictures of rainbows top suffolk realty agents

Contents

Groupchat, : Components, and Event Models


By now, you should have a

good idea of how scripts interact with Jabber and how the core
elements such as <message/> and
<presence/> can be constructed and handled.

This chapter builds upon what we've already seen in Chapter 8 and introduces new concepts. We build a nosy assistant that joins a conference room and alerts us to words and phrases that we want it to listen for. There are two popular conference protocols, as mentioned in Section 6.2.6—the presence-based Groupchat protocol, and the jabber:iq:conference-based Conference protocol. The assistant recipe, a foray into the world of 'bots, takes a look at the original presence-based one.

As we've seen, programming within Jabber's event model is fairly straightforward. But what happens when you want to meld other components with event models of their own? We look at a couple of typical scenarios where this melding needs to happen. The first is a homage to the Trojan Room Coffee Machine (http://www.cl.cam.ac.uk/coffee/coffee.html), where we give life, or at least presence, to a coffeepot, using LEGO® MINDSTORMS™. The second is a Tk-based RSS headline viewer. Both the coffeepot and the Tk programming library have event loops of their own. With the coffeepot, we need to have a loop that polls the coffeepot's status, independently of the polling for incoming packets from the Jabber server. The Tk programming library's event model is similar to those of the Jabber programming libraries that are used in the recipes in this book, in that handlers are set up and a loop is started that listens for UI events. In both cases, we need to get these event loops to work in harmony with the Jabber libraries' event loops.

Building Jabber solutions without event loops is a Sisyphean task. The very nature of Jabber communication is event-based, and it's important to understand how to use the event features of the Jabber programming libraries and also how to be able to mesh those features with similar features in other libraries and systems.

We also look at extending messages and build a mechanism that delivers RSS headlines to clients who register with that mechanism. These headlines are carried using an extended message type. In fact, the RSS Delivery Mechanism is a component. The three recipes in Chapter 8, were Jabber clients, in that they connected to the Jabber network via the Jabber Session Manager (JSM) service. We look at the differences between programming a client and programming a component in this chapter and build a complete component that can be queried and interacted with using the third of Jabber's building blocks—the <iq/> element.

Happy coding!


Keyword Assistant


Many of the Jabber core and peripheral developers hang out in a conference room called jdev hosted by the Conferencing component on the Jabber server running at jabber.org. While a lot of useful information is to be gleaned from listening to what goes on in jdev, it isn't possible to be there all the time. Conversations in jdev are logged to web pages, which can be used to visit after the fact to try to catch up with things; however, this can be a hopeless task. One solution is to build a 'bot that looks for specific keywords and Uniform Resource Locators (URLs) in the conversations in jdev and send those on as Jabber messages.

This script, keyassist, connects to a Jabber server, enters a conference room, and listens to the conversations, looking for certain words and phrases to be uttered. The keyassist script is given a bit of "intelligence" in that it can be interacted with and told, while running, to watch for (or stop watching for), certain words and phrases.

The keyassist script introduces us to programmatic interaction with the Conferencing component. Before looking at the script, however, let's have a brief overview of Conferencing in general.



Conferencing


The Conferencing component at jabber.org is conference.jabber.org. Details of the component instance configuration for such a Conferencing component can be found in Section 4.10, where we see that the component exists as a shared object library connected with the library load component connection method. This component provides general conferencing facilities, oriented around a conference room and conference user model.

A Jabber user can enter (or join) a conference room, thereby becoming a conference user identified by a nickname that is chosen upon entering that room. Nicknames are generally used in conference rooms to provide a modicum of privacy—it is assumed that by default you don't want to let the other conference room members know your real JID.

The Conferencing component supports two protocols for user and room interaction: a simple one that provides basic features and a more complex one that provides the basic features plus facilities such as password-protected rooms and room descriptions—Groupchat and Conference.


{{Note|There is a third protocol, called Experimentaliq:groupchat, which came between the Groupchat and Conference protocols. This reflected an experimental move to add features to the basic Groupchat protocol using IQ elements, the contents of which were qualified by a namespace jabber:iq:groupchat. This protocol has been dropped, and support for it exists only in certain versions of WinJab and JIM.

</code>

Groupchat
The Groupchat protocol is the simpler of the two and provides basic
functions for entering and exiting conference rooms and choosing
nicknames. : This Groupchat protocol is known as the presence-based
protocol, because the protocol is based upon
<presence/> elements used for room entry, exit, and
nickname determination. The Groupchat protocol has a nominal version
number of 1.0.
Conference
The Conference protocol offers more advanced features than the
Groupchat protocol and makes use of two IQ namespaces:
jabber:iq:conference and jabber:iq:browse. It has a
nominal protocol version number of 1.4, which reflects the version of
the Jabber server with which it is delivered. Sometimes this version
number is referred to as 0.4, such as in the downloadable tarball and
in the value returned in response to a "version query" on the
component itself, as shown in Example 9-1. : The version number isn't
that important. The main thing to keep in mind is that the component
that is called conference.so (see the reference to the
shared object library in Section 4.10.4) supports both the
Groupchat protocol and the Conference protocol. If you come across a
shared object library called groupchat.so, this is the
original Conferencing component that was made available with Jabber
server Version 1.0. This library supports only the Groupchat protocol.

Querying the Conferencing component's version

SEND: <iq type='get' to='conference.gnu.mine.nu'> <query xmlns='jabber:iq:version'/> </iq>

RECV: <iq to='dj@gnu.mine.nu/jarl' from='conference.gnu.mine.nu' type='result'> <query xmlns='jabber:iq:version'> <name>conference</name> <version>0.4</version> <os>Linux 2.4.2-2</os> </query> </iq> In this recipe we'll be using the simpler Groupchat protocol. It's widely used and easy to understand. Example 9-2 shows a typical element log from Groupchat-based activity. It shows a user, with the JID qmacro@jabber.com, entering a room called "cellar," hosted on the conference component at conf.merlix.dyndns.org, a room that currently has two other occupants who go by the nicknames flash and roscoe. The elements are from qmacro's perspective, and are all explained following the example.


The Groupchat protocol in action The user qmacro tries to enter the conference room with the nickname flash and fails:


SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

He tries again, this time with a different nickname, deejay, and is successful:


SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>deejay has become available</body> </message>

roscoe says hi, and qmacro waves back:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=> <body>hi</body> </message>

SEND: <message to='cellar@conf.merlix.dyndns.org' type='groupchat'> <body>/me waves to everyone</body> </message>

flash sends a private message to qmacro:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='chat'> <body>Is that you, qmacro?</body> <thread>jarl1998911094</thread> </message>

Feeling left out of the conversation, roscoe leaves the room:


RECV: <presence to='qmacro@jabber.com/jarltk' type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>roscoe has left</body> </message> Let's take the stages in Example 9-2 one by one.


Failed attempt to enter room
qmacro makes an attempt to enter the room using the Groupchat
protocol. This is done by sending a directed
<presence/> element to a particular JID that represents
the room and the chosen nickname. This JID is constructed as follows:

[room name]@[conference component]/[nickname]

In this example, the conferencing component is identified with the
hostname conf.merlix.dyndns.org. qmacro's choice of
nickname is flash:

cellar@conf.merlix.dyndns.org/flash

Thus the following element is sent:

SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

The conference component determines that there is already someone
present in the room cellar@conf.merlix.dyndns.org with the
nickname flash, so qmacro is notified of this and
receives a directed presence with an <error/> tag:

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

Note that the <presence/> element has the type
error and comes from the artificial JID constructed in the
room entry attempt. The element is addressed to qmacro's real
JID, of course—qmacro@jabber.com/jarltk—as otherwise it
wouldn't reach him. : The error code 409 and text "Conflict" tells
qmacro that the nickname conflicted with one already in the
room. This is a standard error code/text pair; Table 5-3 shows a
complete set of code/text pairs. : At this stage, qmacro is
not yet in the room.
Successful attempt to enter room
qmacro tries again, this time with a different nickname,
deejay:[1]

SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

This time, there is no conflict—no other user is in the room "cellar"
with that nickname—and the conference component registers the entry.
It does this by sending qmacro the presence of all the room
occupants, including that of himself:

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/deejay'/>

These presence elements are also sent to the other room occupants so
they know that deejay is present.
Conference component-generated notification
In addition to the presence elements sent for each room occupant, a
general roomwide message noting that someone with the nickname
deejay just entered the room is sent out by the component as
a type='groupchat' message to all the room occupants:

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>deejay has become available</body> </message>

The text "has become available" used in the body of the message is
taken directly from the Action Notices definitions, part of the
Conferencing component instance configuration described in Section
4.10.3. Note that the identity of the room itself is simply a generic
version of the JID that the room occupants use to enter:

cellar@conf.merlix.dyndns.org

Roomwide chat
Once the user with the nickname roscoe sees someone enter the
room, he sends a greeting, and qmacro waves back:

RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=> <body>hi qmacro</body> </message>

SEND: <message to='cellar@conf.merlix.dyndns.org' type='groupchat'> <body>/me waves to everyone</body> </message>

As with the notification message, each message is a
groupchat-type message. The one received appears to come from
cellar@conf.merlix.dyndns.org/roscoe, which is the JID
representing the user in the room with the nickname roscoe.
This way, roscoe's real JID is never sent to qmacro.
The message deejay sends is addressed to the room's identity
cellar@conf.merlix.dyndns.org, and contains a message that
starts with /me. This is simply a convention that is
understood by clients that support conferencing, meant to represent an
action and displayed thus:

* deejay waves to everyone

{{Note|Ignore the cnu attribute; it's put there and used by the component and should never make it out to the client endpoints. The attribute name is a short name for the conference user and refers to the internal structure that represents a conference room occupant within the component.

</code>

One-on-one chat
The Conferencing component also supports a one-on-one chat mode, which
is just like normal chat mode (where messages with the type
chat are exchanged) except that the routing goes through the
component. The intended recipient of a conference-routed chat message
is identified by his room JID. So in this example:

RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='chat'> <body>Is that you, qmacro?</body> <thread>jarl1998911094</thread> </message>

the user nicknamed flash actually addressed the chat message
to the JID:

cellar@conf.merlix.dyndns.org/deejay

which arrived at the Conferencing component (because of the hostname,
conf.merlix.dyndns.org causes the <message/>
element to be routed there), which then looked up internally who
deejay really was (qmacro@jabber.com/jarltk) and
sent it on. This way, the recipient of a conference-routed message
never discovers the real JID of the sender. In all other ways, the
actual <message/> element is like any other
<message/> element—in this case, it contains a message
<body/> and a chat <thread/>. (See
Section 5.4.1 for details on the <message/> element.)
Leaving the room
In the same way that room entrance is effected by sending an
available presence (remember, a <presence/>
element without an explicit type attribute is understood to
represent type="available'), leaving a room is achieved by
doing the opposite:

RECV: <presence to='qmacro@jabber.com/jarltk' type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/>

The people in the conference room are sent a message that
roscoe has left the room by the unavailable presence
packet. This is by and large for the benefit of each user's client, so
that the room occupant list can be updated. The component also sends
out a verbal notification, in the same way as it sends a verbal
notification out when someone joins:

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>roscoe has left</body> </message>

Like the join notification, the text for the leave notification ("has
left") comes directly from the component instance configuration
described in Section 4.10.3.


The Script's Scope


The Keyword Assistant (keyassist) script will be written in Python using the Jabberpy library. As mentioned earlier, the script will perform the following tasks:

  • Connect to a predetermined Jabber server
  • Join a predetermined conference room
  • Sit there quietly, listening to the conversation
  • Take simple commands from people to watch for, or stop watching for, particular words or phrases uttered in the room
  • Relay the context of those words or phrases to whomever requested them, if heard In addition

to setting the identity of the Jabber server and the conference room in variables, we'll also need to keep track of which users ask the assistant for words and phrases.
We'll use a dictionary (hash in Perl terms), as shown in Example 9-3, because we want to manage the data in there by key, the JID of those users that the script will be assisting. Having a look at what this dictionary will look like during the lifetime of this script will help us to visualize what we're trying to achieve.


Typical contents of the Keyword Assistant's dictionary

{ 'dj@gnu.pipetree.com/home': { 'http:': 1, 'ftp:': 1

                                         },
 'piers@jabber.org/work':                { 'Perl': 1, 'Java': 1, 'SAP
 R/3': 1
                                         },
 'cellar@conf.merlix.dyndns.org/roscoe': { 'dialback': 1
                                         }

}

We can see from the contents of the dictionary in Example 9-3 that three people have asked the script to look out for words and phrases. Two of those people—dj and piers—have interacted with the script directly by sending a normal (or chat) <message/>. The other person, with the conference nickname roscoe, is in the "cellar" room and has sent the script a message routed through the Conference component in the same way that flash sent qmacro a private message in Example 9-2: the JID of the sender belongs to (has the hostname set to) the conference component. Technically, there's nothing to distinguish the three JIDs here; it's just that we know from the name that conf.merlix.dyndns.org is the name that identifies such a component.

If we dissect the dictionary, we can see that:

  • dj wants to be notified if any web or FTP URLs are mentioned.
  • piers is interested in references to two of his favorite

languages and his favorite business software solution.

  • roscoe

is interested in any talk about dialback. We said we'd give the script a little bit of intelligence. This was a reference to the ability for users to interact with the script while it runs, rather than having to give the script a static list of words and phrases in a configuration file. dj, piers, and roscoe have done this by sending the script messages (directly, not within the room) with simple keyword commands, such as:

dj: "watch http:" script: "ok, watching for http:" dj:
"watch gopher:" script: "ok, watching for gopher:" dj:
"watch ftp:" script: "ok, watching for ftp:" dj: "ignore
gopher:" script: "ok, now ignoring gopher:"

...

piers: "list" script: "watching for: Perl, Java, SAP R/3"

...

roscoe: "stop" script: "ok, I've stopped watching"


The keyassist Script


Example 9-4 shows the keyassist script in its entirety. The script is described in detail, step by step, in the next section.


The keyassist Perl script

import jabber from string import split, join, find import sys

keywords = {}

def addword(jid, word): if not keywords.has_key(jid): keywords[jid] = {} keywords[jid][word] = 1

def delword(jid, word): if keywords.has_key(jid): if keywords[jid].has_key(word): del keywords[jid][word]

def messageCB(con, msg):

   type = msg.getType() if type == None: type = 'normal'
   # Deal with interaction
   if type == 'chat' or type == 'normal': jid = str(msg.getFrom())
       message = split(msg.getBody(), None, 1); reply = ""
       if message[0] == 'watch': addword(jid, message[1]) reply =
       "Okay, watching for " + message[1]
       if message[0] == 'ignore': delword(jid, message[1]) reply =
       "Okay, now ignoring " + message[1]
       if message[0] == 'list': if keywords.has_key(jid): reply =
       "Watching for: " + join(keywords[jid].keys(), ", ") else: reply
       = "Not watching for any keywords"
       if message[0] == 'stop': if keywords.has_key(jid): del
       keywords[jid] reply = "Okay, I've stopped watching"
       if reply: con.send(msg.build_reply(reply))


   # Scan room talk
   if type == 'groupchat': message = msg.getBody()
       for jid in keywords.keys(): for word in keywords[jid].keys(): if
       find(message, word) >= 0: con.send(jabber.Message(jid, word +
       ": " + message))


def presenceCB(con, prs):

   # Deal with nickname conflict in room
   if str(prs.getFrom()) == roomjid and prs.getType() == 'error':
   prsnode = prs.asNode() error = prsnode.getTag('error') if error: if
   (error.getAttr('code') == '409'): print "Cannot join room -
   conflicting nickname" con.disconnect() sys.exit(0)
   # Remove keyword list for groupchat correspondent
   if prs.getType() == 'unavailable': jid = str(prs.getFrom()) if
   keywords.has_key(jid): del keywords[jid]

Server = 'gnu.mine.nu' Username = 'kassist' Password = 'pass' Resource = 'py'

Room = 'jdev' ConfServ = 'conference.jabber.org' Nick = 'kassist'

con = jabber.Client(host=Server) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected"

if con.auth(Username,Password,Resource): print "Logged in as %s to server %s" % ( Username, Server ) else: print "Problems authenticating: ", con.lastErr, con.lastErrCode sys.exit(1)

con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB)

con.send(jabber.Presence())

roomjid = Room + '@' + ConfServ + '/' + Nick print "Joining " + Room con.send(jabber.Presence(to=roomjid))

while(1): con.process(5)


Dissecting the keyassist Script


Taking keyassist step by step, the first section is probably familiar if you've seen the previous Python-based scripts in Section 8.1 and Section 8.3, both in Chapter 8.


import jabber from string import split, join, find import sys

Here, all of the functions and libraries that we'll need are brought in. We'll use the find function from the string library to help with the keyword searching.

Next, we declare the dictionary. This will hold a list of the words that the script will look for, as defined by each person, as shown in Example 9-3.


keywords = {}


Maintaining the keyword dictionary


To maintain this dictionary, we will use two subroutines to add words to and remove words from a user's word list. These subroutines are called when a command such as watch or ignore is recognized in the callback subroutine that handles incoming <message/> elements:


def addword(jid, word): if not keywords.has_key(jid): keywords[jid] = {} keywords[jid][word] = 1

def delword(jid, word): if keywords.has_key(jid): if keywords[jid].has_key(word): del keywords[jid][word]

A string representation of the JID (in jid) of the correspondent giving the command is passed to the subroutines along with the word or phrase specified (in word) by the user. The dictionary has two levels: the first level is keyed by the JID, and the second by word or phrase. We use a dictionary, rather than an array, at the second level simply to make removal of words and phrases easier.



Message callback


Next, we define the callback to handle incoming <message/> elements:


def messageCB(con, msg):

   type = msg.getType() if type == None: type = 'normal'

As usual, we're expecting the message callback to be passed the connection object (in con) and the message object itself (msg). How this callback is to proceed is determined by the type of message received. We determine the type (taken from the <message/> element's type attribute) and store it in the variable called type. Remember that if no type attribute is present, a message type of normal is assumed. (See Section 5.4.1.1 for details of <message/> attributes.)

The two types of incoming messages we're expecting this script to receive are those conveying the room's conversation—in groupchat-type messagesâ€ÃÃÃÂ�

Personal tools