001/**
002 *
003 * Copyright 2003-2006 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.filetransfer;
018
019import java.io.InputStream;
020import java.io.OutputStream;
021
022import org.jivesoftware.smack.Manager;
023import org.jivesoftware.smack.SmackException;
024import org.jivesoftware.smack.SmackException.NoResponseException;
025import org.jivesoftware.smack.SmackException.NotConnectedException;
026import org.jivesoftware.smack.XMPPConnection;
027import org.jivesoftware.smack.XMPPException;
028import org.jivesoftware.smack.XMPPException.XMPPErrorException;
029import org.jivesoftware.smack.packet.IQ;
030import org.jivesoftware.smack.packet.Stanza;
031import org.jivesoftware.smack.util.EventManger;
032import org.jivesoftware.smack.util.EventManger.Callback;
033
034import org.jivesoftware.smackx.si.packet.StreamInitiation;
035import org.jivesoftware.smackx.xdata.FormField;
036import org.jivesoftware.smackx.xdata.packet.DataForm;
037
038import org.jxmpp.jid.Jid;
039
040/**
041 * After the file transfer negotiation process is completed according to
042 * XEP-0096, the negotiation process is passed off to a particular stream
043 * negotiator. The stream negotiator will then negotiate the chosen stream and
044 * return the stream to transfer the file.
045 *
046 * @author Alexander Wenckus
047 */
048public abstract class StreamNegotiator extends Manager {
049
050    protected StreamNegotiator(XMPPConnection connection) {
051        super(connection);
052    }
053
054    /**
055     * A event manager for stream initiation requests send to us.
056     * <p>
057     * Those are typical XEP-45 Open or XEP-65 Bytestream IQ requests. The even key is in the format
058     * "initiationFrom + '\t' + streamId"
059     * </p>
060     */
061    // TODO This field currently being static is considered a quick hack. Ideally this should take
062    // the local connection into account, for example by changing the key to
063    // "localJid + '\t' + initiationFrom + '\t' + streamId" or making the field non-static (but then
064    // you need to provide access to the InitiationListeners, which could get tricky)
065    protected static final EventManger<String, IQ, SmackException.NotConnectedException> initationSetEvents = new EventManger<>();
066
067    /**
068     * Creates the initiation acceptance stanza(/packet) to forward to the stream
069     * initiator.
070     *
071     * @param streamInitiationOffer The offer from the stream initiator to connect for a stream.
072     * @param namespaces            The namespace that relates to the accepted means of transfer.
073     * @return The response to be forwarded to the initiator.
074     */
075    protected static StreamInitiation createInitiationAccept(
076            StreamInitiation streamInitiationOffer, String[] namespaces)
077    {
078        StreamInitiation response = new StreamInitiation();
079        response.setTo(streamInitiationOffer.getFrom());
080        response.setFrom(streamInitiationOffer.getTo());
081        response.setType(IQ.Type.result);
082        response.setStanzaId(streamInitiationOffer.getStanzaId());
083
084        DataForm form = new DataForm(DataForm.Type.submit);
085        FormField field = new FormField(
086                FileTransferNegotiator.STREAM_DATA_FIELD_NAME);
087        for (String namespace : namespaces) {
088            field.addValue(namespace);
089        }
090        form.addField(field);
091
092        response.setFeatureNegotiationForm(form);
093        return response;
094    }
095
096    protected final IQ initiateIncomingStream(final XMPPConnection connection, StreamInitiation initiation)
097                    throws NoResponseException, XMPPErrorException, NotConnectedException {
098        final StreamInitiation response = createInitiationAccept(initiation,
099                getNamespaces());
100
101        newStreamInitiation(initiation.getFrom(), initiation.getSessionID());
102
103        final String eventKey = initiation.getFrom().toString() + '\t' + initiation.getSessionID();
104        IQ streamMethodInitiation;
105        try {
106            streamMethodInitiation = initationSetEvents.performActionAndWaitForEvent(eventKey, connection.getReplyTimeout(), new Callback<NotConnectedException>() {
107                @Override
108                public void action() throws NotConnectedException {
109                    try {
110                        connection.sendStanza(response);
111                    }
112                    catch (InterruptedException e) {
113                        // Ignore
114                    }
115                }
116            });
117        }
118        catch (InterruptedException e) {
119            // TODO remove this try/catch once merged into 4.2's master branch
120            throw new IllegalStateException(e);
121        }
122
123        if (streamMethodInitiation == null) {
124            throw NoResponseException.newWith(connection, "stream initiation");
125        }
126        XMPPErrorException.ifHasErrorThenThrow(streamMethodInitiation);
127        return streamMethodInitiation;
128    }
129
130    /**
131     * Signal that a new stream initiation arrived. The negotiator may needs to prepare for it.
132     *
133     * @param from     The initiator of the file transfer.
134     * @param streamID The stream ID related to the transfer.
135     */
136    protected abstract void newStreamInitiation(Jid from, String streamID);
137
138
139    abstract InputStream negotiateIncomingStream(Stanza streamInitiation) throws XMPPErrorException,
140            InterruptedException, SmackException;
141
142    /**
143     * This method handles the file stream download negotiation process. The
144     * appropriate stream negotiator's initiate incoming stream is called after
145     * an appropriate file transfer method is selected. The manager will respond
146     * to the initiator with the selected means of transfer, then it will handle
147     * any negotiation specific to the particular transfer method. This method
148     * returns the InputStream, ready to transfer the file.
149     *
150     * @param initiation The initiation that triggered this download.
151     * @return After the negotiation process is complete, the InputStream to
152     *         write a file to is returned.
153     * @throws XMPPErrorException If an error occurs during this process an XMPPException is
154     *                       thrown.
155     * @throws InterruptedException If thread is interrupted.
156     * @throws SmackException 
157     */
158    public abstract InputStream createIncomingStream(StreamInitiation initiation)
159            throws XMPPErrorException, InterruptedException, SmackException;
160
161    /**
162     * This method handles the file upload stream negotiation process. The
163     * particular stream negotiator is determined during the file transfer
164     * negotiation process. This method returns the OutputStream to transmit the
165     * file to the remote user.
166     *
167     * @param streamID  The streamID that uniquely identifies the file transfer.
168     * @param initiator The fully-qualified JID of the initiator of the file transfer.
169     * @param target    The fully-qualified JID of the target or receiver of the file
170     *                  transfer.
171     * @return The negotiated stream ready for data.
172     * @throws SmackException 
173     * @throws XMPPException 
174     * @throws InterruptedException 
175     */
176    public abstract OutputStream createOutgoingStream(String streamID,
177            Jid initiator, Jid target) throws SmackException, XMPPException, InterruptedException;
178
179    /**
180     * Returns the XMPP namespace reserved for this particular type of file
181     * transfer.
182     *
183     * @return Returns the XMPP namespace reserved for this particular type of
184     *         file transfer.
185     */
186    public abstract String[] getNamespaces();
187
188    public static void signal(String eventKey, IQ eventValue) {
189        initationSetEvents.signalEvent(eventKey, eventValue);
190    }
191}