/** * $RCSfile$ * $Revision: 38648 $ * $Date: 2006-12-27 01:46:18 -0800 (Wed, 27 Dec 2006) $ * * Copyright (C) 2003-2005 Jive Software. All rights reserved. * * This software is the proprietary information of Jive Software. * Use is subject to license terms. */ package org.jivesoftware.smackx.workgroup.user; import org.jivesoftware.smackx.workgroup.MetaData; import org.jivesoftware.smackx.workgroup.WorkgroupInvitation; import org.jivesoftware.smackx.workgroup.WorkgroupInvitationListener; import org.jivesoftware.smackx.workgroup.ext.forms.WorkgroupForm; import org.jivesoftware.smackx.workgroup.packet.DepartQueuePacket; import org.jivesoftware.smackx.workgroup.packet.QueueUpdate; import org.jivesoftware.smackx.workgroup.packet.SessionID; import org.jivesoftware.smackx.workgroup.packet.UserID; import org.jivesoftware.smackx.workgroup.settings.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.filter.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.Form; import org.jivesoftware.smackx.FormField; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.packet.DataForm; import org.jivesoftware.smackx.packet.DiscoverInfo; import org.jivesoftware.smackx.packet.MUCUser; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Provides workgroup services for users. Users can join the workgroup queue, depart the * queue, find status information about their placement in the queue, and register to * be notified when they are routed to an agent.
*
* This class only provides a users perspective into a workgroup and is not intended * for use by agents. * * @author Matt Tucker * @author Derek DeMoro */ public class Workgroup { private String workgroupJID; private XMPPConnection connection; private boolean inQueue; private List invitationListeners; private List queueListeners; private List siteInviteListeners; private int queuePosition = -1; private int queueRemainingTime = -1; /** * Creates a new workgroup instance using the specified workgroup JID * (eg support@workgroup.example.com) and XMPP connection. The connection must have * undergone a successful login before being used to construct an instance of * this class. * * @param workgroupJID the JID of the workgroup. * @param connection an XMPP connection which must have already undergone a * successful login. */ public Workgroup(String workgroupJID, XMPPConnection connection) { // Login must have been done before passing in connection. if (!connection.isAuthenticated()) { throw new IllegalStateException("Must login to server before creating workgroup."); } this.workgroupJID = workgroupJID; this.connection = connection; inQueue = false; invitationListeners = new ArrayList(); queueListeners = new ArrayList(); siteInviteListeners = new ArrayList(); // Register as a queue listener for internal usage by this instance. addQueueListener(new QueueListener() { public void joinedQueue() { inQueue = true; } public void departedQueue() { inQueue = false; queuePosition = -1; queueRemainingTime = -1; } public void queuePositionUpdated(int currentPosition) { queuePosition = currentPosition; } public void queueWaitTimeUpdated(int secondsRemaining) { queueRemainingTime = secondsRemaining; } }); /** * Internal handling of an invitation.Recieving an invitation removes the user from the queue. */ MultiUserChat.addInvitationListener(connection, new org.jivesoftware.smackx.muc.InvitationListener() { public void invitationReceived(XMPPConnection conn, String room, String inviter, String reason, String password, Message message) { inQueue = false; queuePosition = -1; queueRemainingTime = -1; } }); // Register a packet listener for all the messages sent to this client. PacketFilter typeFilter = new PacketTypeFilter(Message.class); connection.addPacketListener(new PacketListener() { public void processPacket(Packet packet) { handlePacket(packet); } }, typeFilter); } /** * Returns the name of this workgroup (eg support@example.com). * * @return the name of the workgroup. */ public String getWorkgroupJID() { return workgroupJID; } /** * Returns true if the user is currently waiting in the workgroup queue. * * @return true if currently waiting in the queue. */ public boolean isInQueue() { return inQueue; } /** * Returns true if the workgroup is available for receiving new requests. The workgroup will be * available only when agents are available for this workgroup. * * @return true if the workgroup is available for receiving new requests. */ public boolean isAvailable() { Presence directedPresence = new Presence(Presence.Type.available); directedPresence.setTo(workgroupJID); PacketFilter typeFilter = new PacketTypeFilter(Presence.class); PacketFilter fromFilter = new FromContainsFilter(workgroupJID); PacketCollector collector = connection.createPacketCollector(new AndFilter(fromFilter, typeFilter)); connection.sendPacket(directedPresence); Presence response = (Presence)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { return false; } else if (response.getError() != null) { return false; } else { return Presence.Type.available == response.getType(); } } /** * Returns the users current position in the workgroup queue. A value of 0 means * the user is next in line to be routed; therefore, if the queue position * is being displayed to the end user it is usually a good idea to add 1 to * the value this method returns before display. If the user is not currently * waiting in the workgroup, or no queue position information is available, -1 * will be returned. * * @return the user's current position in the workgroup queue, or -1 if the * position isn't available or if the user isn't in the queue. */ public int getQueuePosition() { return queuePosition; } /** * Returns the estimated time (in seconds) that the user has to left wait in * the workgroup queue before being routed. If the user is not currently waiting * int he workgroup, or no queue time information is available, -1 will be * returned. * * @return the estimated time remaining (in seconds) that the user has to * wait inthe workgroupu queue, or -1 if time information isn't available * or if the user isn't int the queue. */ public int getQueueRemainingTime() { return queueRemainingTime; } /** * Joins the workgroup queue to wait to be routed to an agent. After joining * the queue, queue status events will be sent to indicate the user's position and * estimated time left in the queue. Once joining the queue, there are three ways * the user can leave the queue:*
* Some servers may be configured to require certain meta-data in order to * join the queue. In that case, the {@link #joinQueue(Form)} method should be * used instead of this method so that meta-data may be passed in.*
* The server tracks the conversations that a user has with agents over time. By * default, that tracking is done using the user's JID. However, this is not always * possible. For example, when the user is logged in anonymously using a web client. * In that case the user ID might be a randomly generated value put into a persistent * cookie or a username obtained via the session. A userID can be explicitly * passed in by using the {@link #joinQueue(Form, String)} method. When specified, * that userID will be used instead of the user's JID to track conversations. The * server will ignore a manually specified userID if the user's connection to the server * is not anonymous. * * @throws XMPPException if an error occured joining the queue. An error may indicate * that a connection failure occured or that the server explicitly rejected the * request to join the queue. */ public void joinQueue() throws XMPPException { joinQueue(null); } /** * Joins the workgroup queue to wait to be routed to an agent. After joining * the queue, queue status events will be sent to indicate the user's position and * estimated time left in the queue. Once joining the queue, there are three ways * the user can leave the queue:*
* Some servers may be configured to require certain meta-data in order to * join the queue.*
* The server tracks the conversations that a user has with agents over time. By * default, that tracking is done using the user's JID. However, this is not always * possible. For example, when the user is logged in anonymously using a web client. * In that case the user ID might be a randomly generated value put into a persistent * cookie or a username obtained via the session. A userID can be explicitly * passed in by using the {@link #joinQueue(Form, String)} method. When specified, * that userID will be used instead of the user's JID to track conversations. The * server will ignore a manually specified userID if the user's connection to the server * is not anonymous. * * @param answerForm the completed form the send for the join request. * @throws XMPPException if an error occured joining the queue. An error may indicate * that a connection failure occured or that the server explicitly rejected the * request to join the queue. */ public void joinQueue(Form answerForm) throws XMPPException { joinQueue(answerForm, null); } /** *Joins the workgroup queue to wait to be routed to an agent. After joining * the queue, queue status events will be sent to indicate the user's position and * estimated time left in the queue. Once joining the queue, there are three ways * the user can leave the queue:
*
* Some servers may be configured to require certain meta-data in order to * join the queue.*
* The server tracks the conversations that a user has with agents over time. By * default, that tracking is done using the user's JID. However, this is not always * possible. For example, when the user is logged in anonymously using a web client. * In that case the user ID might be a randomly generated value put into a persistent * cookie or a username obtained via the session. When specified, that userID will * be used instead of the user's JID to track conversations. The server will ignore a * manually specified userID if the user's connection to the server is not anonymous. * * @param answerForm the completed form associated with the join reqest. * @param userID String that represents the ID of the user when using anonymous sessions * or null if a userID should not be used. * @throws XMPPException if an error occured joining the queue. An error may indicate * that a connection failure occured or that the server explicitly rejected the * request to join the queue. */ public void joinQueue(Form answerForm, String userID) throws XMPPException { // If already in the queue ignore the join request. if (inQueue) { throw new IllegalStateException("Already in queue " + workgroupJID); } JoinQueuePacket joinPacket = new JoinQueuePacket(workgroupJID, answerForm, userID); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(joinPacket.getPacketID())); this.connection.sendPacket(joinPacket); IQ response = (IQ)collector.nextResult(10000); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from the server."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } // Notify listeners that we've joined the queue. fireQueueJoinedEvent(); } /** *Joins the workgroup queue to wait to be routed to an agent. After joining * the queue, queue status events will be sent to indicate the user's position and * estimated time left in the queue. Once joining the queue, there are three ways * the user can leave the queue:
*
* Some servers may be configured to require certain meta-data in order to * join the queue.*
* The server tracks the conversations that a user has with agents over time. By * default, that tracking is done using the user's JID. However, this is not always * possible. For example, when the user is logged in anonymously using a web client. * In that case the user ID might be a randomly generated value put into a persistent * cookie or a username obtained via the session. When specified, that userID will * be used instead of the user's JID to track conversations. The server will ignore a * manually specified userID if the user's connection to the server is not anonymous. * * @param metadata metadata to create a dataform from. * @param userID String that represents the ID of the user when using anonymous sessions * or null if a userID should not be used. * @throws XMPPException if an error occured joining the queue. An error may indicate * that a connection failure occured or that the server explicitly rejected the * request to join the queue. */ public void joinQueue(Map metadata, String userID) throws XMPPException { // If already in the queue ignore the join request. if (inQueue) { throw new IllegalStateException("Already in queue " + workgroupJID); } // Build dataform from metadata Form form = new Form(Form.TYPE_SUBMIT); Iterator iter = metadata.keySet().iterator(); while (iter.hasNext()) { String name = (String)iter.next(); String value = (String)metadata.get(name).toString(); String escapedName = StringUtils.escapeForXML(name); String escapedValue = StringUtils.escapeForXML(value); FormField field = new FormField(escapedName); field.setType(FormField.TYPE_TEXT_SINGLE); form.addField(field); form.setAnswer(escapedName, escapedValue); } joinQueue(form, userID); } /** * Departs the workgroup queue. If the user is not currently in the queue, this * method will do nothing.*
* Normally, the user would not manually leave the queue. However, they may wish to * under certain circumstances -- for example, if they no longer wish to be routed * to an agent because they've been waiting too long. * * @throws XMPPException if an error occured trying to send the depart queue * request to the server. */ public void departQueue() throws XMPPException { // If not in the queue ignore the depart request. if (!inQueue) { return; } DepartQueuePacket departPacket = new DepartQueuePacket(this.workgroupJID); PacketCollector collector = this.connection.createPacketCollector(new PacketIDFilter(departPacket.getPacketID())); connection.sendPacket(departPacket); IQ response = (IQ)collector.nextResult(5000); collector.cancel(); if (response == null) { throw new XMPPException("No response from the server."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } // Notify listeners that we're no longer in the queue. fireQueueDepartedEvent(); } /** * Adds a queue listener that will be notified of queue events for the user * that created this Workgroup instance. * * @param queueListener the queue listener. */ public void addQueueListener(QueueListener queueListener) { synchronized (queueListeners) { if (!queueListeners.contains(queueListener)) { queueListeners.add(queueListener); } } } /** * Removes a queue listener. * * @param queueListener the queue listener. */ public void removeQueueListener(QueueListener queueListener) { synchronized (queueListeners) { queueListeners.remove(queueListener); } } /** * Adds an invitation listener that will be notified of groupchat invitations * from the workgroup for the the user that created this Workgroup instance. * * @param invitationListener the invitation listener. */ public void addInvitationListener(WorkgroupInvitationListener invitationListener) { synchronized (invitationListeners) { if (!invitationListeners.contains(invitationListener)) { invitationListeners.add(invitationListener); } } } /** * Removes an invitation listener. * * @param invitationListener the invitation listener. */ public void removeQueueListener(WorkgroupInvitationListener invitationListener) { synchronized (invitationListeners) { invitationListeners.remove(invitationListener); } } private void fireInvitationEvent(WorkgroupInvitation invitation) { synchronized (invitationListeners) { for (Iterator i = invitationListeners.iterator(); i.hasNext();) { WorkgroupInvitationListener listener = (WorkgroupInvitationListener)i.next(); listener.invitationReceived(invitation); } } } private void fireQueueJoinedEvent() { synchronized (queueListeners) { for (Iterator i = queueListeners.iterator(); i.hasNext();) { QueueListener listener = (QueueListener)i.next(); listener.joinedQueue(); } } } private void fireQueueDepartedEvent() { synchronized (queueListeners) { for (Iterator i = queueListeners.iterator(); i.hasNext();) { QueueListener listener = (QueueListener)i.next(); listener.departedQueue(); } } } private void fireQueuePositionEvent(int currentPosition) { synchronized (queueListeners) { for (Iterator i = queueListeners.iterator(); i.hasNext();) { QueueListener listener = (QueueListener)i.next(); listener.queuePositionUpdated(currentPosition); } } } private void fireQueueTimeEvent(int secondsRemaining) { synchronized (queueListeners) { for (Iterator i = queueListeners.iterator(); i.hasNext();) { QueueListener listener = (QueueListener)i.next(); listener.queueWaitTimeUpdated(secondsRemaining); } } } // PacketListener Implementation. private void handlePacket(Packet packet) { if (packet instanceof Message) { Message msg = (Message)packet; // Check to see if the user left the queue. PacketExtension pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup"); PacketExtension queueStatus = msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup"); if (pe != null) { fireQueueDepartedEvent(); } else if (queueStatus != null) { QueueUpdate queueUpdate = (QueueUpdate)queueStatus; if (queueUpdate.getPosition() != -1) { fireQueuePositionEvent(queueUpdate.getPosition()); } if (queueUpdate.getRemaingTime() != -1) { fireQueueTimeEvent(queueUpdate.getRemaingTime()); } } else { // Check if a room invitation was sent and if the sender is the workgroup MUCUser mucUser = (MUCUser)msg.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null; if (invite != null && workgroupJID.equals(invite.getFrom())) { String sessionID = null; Map metaData = null; pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE); if (pe != null) { sessionID = ((SessionID)pe).getSessionID(); } pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE); if (pe != null) { metaData = ((MetaData)pe).getMetaData(); } WorkgroupInvitation inv = new WorkgroupInvitation(connection.getUser(), msg.getFrom(), workgroupJID, sessionID, msg.getBody(), msg.getFrom(), metaData); fireInvitationEvent(inv); } } } } /** * IQ packet to request joining the workgroup queue. */ private class JoinQueuePacket extends IQ { private String userID = null; private DataForm form; public JoinQueuePacket(String workgroup, Form answerForm, String userID) { this.userID = userID; setTo(workgroup); setType(IQ.Type.SET); form = answerForm.getDataFormToSend(); addExtension(form); } public String getChildElementXML() { StringBuilder buf = new StringBuilder(); buf.append("