JingleConnectionManager.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import android.os.SystemClock;
  4import android.util.Base64;
  5import android.util.Log;
  6
  7import com.google.common.base.Function;
  8import com.google.common.base.Objects;
  9import com.google.common.base.Preconditions;
 10import com.google.common.cache.Cache;
 11import com.google.common.cache.CacheBuilder;
 12import com.google.common.collect.Collections2;
 13import com.google.common.collect.ImmutableSet;
 14
 15import org.checkerframework.checker.nullness.compatqual.NullableDecl;
 16
 17import java.lang.ref.WeakReference;
 18import java.security.SecureRandom;
 19import java.util.Collection;
 20import java.util.Collections;
 21import java.util.HashMap;
 22import java.util.List;
 23import java.util.Map;
 24import java.util.Set;
 25import java.util.concurrent.ConcurrentHashMap;
 26import java.util.concurrent.Executors;
 27import java.util.concurrent.ScheduledExecutorService;
 28import java.util.concurrent.ScheduledFuture;
 29import java.util.concurrent.TimeUnit;
 30
 31import eu.siacs.conversations.Config;
 32import eu.siacs.conversations.entities.Account;
 33import eu.siacs.conversations.entities.Contact;
 34import eu.siacs.conversations.entities.Conversation;
 35import eu.siacs.conversations.entities.Conversational;
 36import eu.siacs.conversations.entities.Message;
 37import eu.siacs.conversations.entities.RtpSessionStatus;
 38import eu.siacs.conversations.entities.Transferable;
 39import eu.siacs.conversations.services.AbstractConnectionManager;
 40import eu.siacs.conversations.services.XmppConnectionService;
 41import eu.siacs.conversations.xml.Element;
 42import eu.siacs.conversations.xml.Namespace;
 43import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 44import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
 45import eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription;
 46import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
 47import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 48import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
 49import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 50import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
 51import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 52import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 53import rocks.xmpp.addr.Jid;
 54
 55public class JingleConnectionManager extends AbstractConnectionManager {
 56    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
 57    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals = new HashMap<>();
 58    private final Map<AbstractJingleConnection.Id, AbstractJingleConnection> connections = new ConcurrentHashMap<>();
 59
 60    private final Cache<PersistableSessionId, JingleRtpConnection.State> endedSessions = CacheBuilder.newBuilder()
 61            .expireAfterWrite(30, TimeUnit.MINUTES)
 62            .build();
 63
 64    private HashMap<Jid, JingleCandidate> primaryCandidates = new HashMap<>();
 65
 66    public JingleConnectionManager(XmppConnectionService service) {
 67        super(service);
 68    }
 69
 70    static String nextRandomId() {
 71        final byte[] id = new byte[16];
 72        new SecureRandom().nextBytes(id);
 73        return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING);
 74    }
 75
 76    public void deliverPacket(final Account account, final JinglePacket packet) {
 77        final String sessionId = packet.getSessionId();
 78        if (sessionId == null) {
 79            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
 80            return;
 81        }
 82        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
 83        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 84        if (existingJingleConnection != null) {
 85            existingJingleConnection.deliverPacket(packet);
 86        } else if (packet.getAction() == JinglePacket.Action.SESSION_INITIATE) {
 87            final Jid from = packet.getFrom();
 88            final Content content = packet.getJingleContent();
 89            final String descriptionNamespace = content == null ? null : content.getDescriptionNamespace();
 90            final AbstractJingleConnection connection;
 91            if (FileTransferDescription.NAMESPACES.contains(descriptionNamespace)) {
 92                connection = new JingleFileTransferConnection(this, id, from);
 93            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace) && !usesTor(account)) {
 94                final boolean sessionEnded = this.endedSessions.asMap().containsKey(PersistableSessionId.of(id));
 95                final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 96                if (isBusy() || sessionEnded || stranger) {
 97                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": rejected session with " + id.with + " because busy. sessionEnded=" + sessionEnded + ", stranger=" + stranger);
 98                    mXmppConnectionService.sendIqPacket(account, packet.generateResponse(IqPacket.TYPE.RESULT), null);
 99                    final JinglePacket sessionTermination = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
100                    sessionTermination.setTo(id.with);
101                    sessionTermination.setReason(Reason.BUSY, null);
102                    mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
103                    return;
104                }
105                connection = new JingleRtpConnection(this, id, from);
106            } else {
107                respondWithJingleError(account, packet, "unsupported-info", "feature-not-implemented", "cancel");
108                return;
109            }
110            connections.put(id, connection);
111            connection.deliverPacket(packet);
112        } else {
113            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
114            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
115        }
116    }
117
118    private boolean usesTor(final Account account) {
119        return account.isOnion() || mXmppConnectionService.useTorToConnect();
120    }
121
122    public boolean isBusy() {
123        for (AbstractJingleConnection connection : this.connections.values()) {
124            if (connection instanceof JingleRtpConnection) {
125                if (((JingleRtpConnection) connection).isTerminated()) {
126                    continue;
127                }
128                return true;
129            }
130        }
131        synchronized (this.rtpSessionProposals) {
132            return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED) || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING);
133        }
134    }
135
136    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
137        final boolean notifyForStrangers = mXmppConnectionService.getNotificationService().notificationsFromStrangers();
138        if (notifyForStrangers) {
139            return false;
140        }
141        final Contact contact = account.getRoster().getContact(with);
142        return !contact.showInContactList();
143    }
144
145    ScheduledFuture<?> schedule(final Runnable runnable, final long delay, final TimeUnit timeUnit) {
146        return this.scheduledExecutorService.schedule(runnable, delay, timeUnit);
147    }
148
149    void respondWithJingleError(final Account account, final IqPacket original, String jingleCondition, String condition, String conditionType) {
150        final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
151        final Element error = response.addChild("error");
152        error.setAttribute("type", conditionType);
153        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
154        error.addChild(jingleCondition, "urn:xmpp:jingle:errors:1");
155        account.getXmppConnection().sendIqPacket(response, null);
156    }
157
158    public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message, String serverMsgId, long timestamp) {
159        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
160        final String sessionId = message.getAttribute("id");
161        if (sessionId == null) {
162            return;
163        }
164        if ("accept".equals(message.getName())) {
165            for (AbstractJingleConnection connection : connections.values()) {
166                if (connection instanceof JingleRtpConnection) {
167                    final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
168                    final AbstractJingleConnection.Id id = connection.getId();
169                    if (id.account == account && id.sessionId.equals(sessionId)) {
170                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
171                        return;
172                    }
173                }
174            }
175            return;
176        }
177        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
178        final AbstractJingleConnection.Id id;
179        if (fromSelf) {
180            if (to != null && to.isFullJid()) {
181                id = AbstractJingleConnection.Id.of(account, to, sessionId);
182            } else {
183                return;
184            }
185        } else {
186            id = AbstractJingleConnection.Id.of(account, from, sessionId);
187        }
188        final AbstractJingleConnection existingJingleConnection = connections.get(id);
189        if (existingJingleConnection != null) {
190            if (existingJingleConnection instanceof JingleRtpConnection) {
191                ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message, serverMsgId, timestamp);
192            } else {
193                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
194            }
195            return;
196        }
197
198        if (fromSelf) {
199            if ("proceed".equals(message.getName())) {
200                final Conversation c = mXmppConnectionService.findOrCreateConversation(account, id.with, false, false);
201                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
202                if (previousBusy != null) {
203                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
204                    if (serverMsgId != null) {
205                        previousBusy.setServerMsgId(serverMsgId);
206                    }
207                    previousBusy.setTime(timestamp);
208                    mXmppConnectionService.updateMessage(previousBusy, true);
209                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": updated previous busy because call got picked up by another device");
210                    return;
211                }
212            }
213            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
214            return;
215        }
216
217        if ("propose".equals(message.getName())) {
218            final Propose propose = Propose.upgrade(message);
219            final List<GenericDescription> descriptions = propose.getDescriptions();
220            final Collection<RtpDescription> rtpDescriptions = Collections2.transform(
221                    Collections2.filter(descriptions, d -> d instanceof RtpDescription),
222                    input -> (RtpDescription) input
223            );
224            if (rtpDescriptions.size() > 0 && rtpDescriptions.size() == descriptions.size() && !usesTor(account)) {
225                final Collection<Media> media = Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
226                if (media.contains(Media.UNKNOWN)) {
227                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered unknown media in session proposal. " + propose);
228                    return;
229                }
230                final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
231                if (isBusy() || stranger) {
232                    writeLogMissedIncoming(account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
233                    if (stranger) {
234                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring call proposal from stranger " + id.with);
235                        return;
236                    }
237                    final int activeDevices = account.countPresences();
238                    Log.d(Config.LOGTAG, "active devices: " + activeDevices);
239                    if (activeDevices == 0) {
240                        final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
241                        mXmppConnectionService.sendMessagePacket(account, reject);
242                    } else {
243                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring proposal because busy on this device but there are other devices");
244                    }
245                } else {
246                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
247                    this.connections.put(id, rtpConnection);
248                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
249                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
250                }
251            } else {
252                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed session with " + rtpDescriptions.size() + " rtp descriptions of " + descriptions.size() + " total descriptions");
253            }
254        } else if ("proceed".equals(message.getName())) {
255            synchronized (rtpSessionProposals) {
256                final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
257                if (proposal != null) {
258                    rtpSessionProposals.remove(proposal);
259                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
260                    rtpConnection.setProposedMedia(proposal.media);
261                    this.connections.put(id, rtpConnection);
262                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
263                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
264                } else {
265                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
266                }
267            }
268        } else if ("reject".equals(message.getName())) {
269            final RtpSessionProposal proposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
270            synchronized (rtpSessionProposals) {
271                if (rtpSessionProposals.remove(proposal) != null) {
272                    writeLogMissedOutgoing(account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
273                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
274                } else {
275                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
276                }
277            }
278        } else {
279            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
280        }
281
282    }
283
284    private RtpSessionProposal getRtpSessionProposal(final Account account, Jid from, String sessionId) {
285        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
286            if (rtpSessionProposal.sessionId.equals(sessionId) && rtpSessionProposal.with.equals(from) && rtpSessionProposal.account.getJid().equals(account.getJid())) {
287                return rtpSessionProposal;
288            }
289        }
290        return null;
291    }
292
293    private void writeLogMissedOutgoing(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
294        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
295                account,
296                with.asBareJid(),
297                false,
298                false
299        );
300        final Message message = new Message(
301                conversation,
302                Message.STATUS_SEND,
303                Message.TYPE_RTP_SESSION,
304                sessionId
305        );
306        message.setBody(new RtpSessionStatus(false, 0).toString());
307        message.setServerMsgId(serverMsgId);
308        message.setTime(timestamp);
309        writeMessage(message);
310    }
311
312    private void writeLogMissedIncoming(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
313        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
314                account,
315                with.asBareJid(),
316                false,
317                false
318        );
319        final Message message = new Message(
320                conversation,
321                Message.STATUS_RECEIVED,
322                Message.TYPE_RTP_SESSION,
323                sessionId
324        );
325        message.setBody(new RtpSessionStatus(false, 0).toString());
326        message.setServerMsgId(serverMsgId);
327        message.setTime(timestamp);
328        writeMessage(message);
329    }
330
331    private void writeMessage(final Message message) {
332        final Conversational conversational = message.getConversation();
333        if (conversational instanceof Conversation) {
334            ((Conversation) conversational).add(message);
335            mXmppConnectionService.databaseBackend.createMessage(message);
336            mXmppConnectionService.updateConversationUi();
337        } else {
338            throw new IllegalStateException("Somehow the conversation in a message was a stub");
339        }
340    }
341
342    public void startJingleFileTransfer(final Message message) {
343        Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
344        final Transferable old = message.getTransferable();
345        if (old != null) {
346            old.cancel();
347        }
348        final Account account = message.getConversation().getAccount();
349        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
350        final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
351        mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
352        this.connections.put(id, connection);
353        connection.init(message);
354    }
355
356    void finishConnection(final AbstractJingleConnection connection) {
357        this.connections.remove(connection.getId());
358    }
359
360    void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
361        if (Config.DISABLE_PROXY_LOOKUP) {
362            listener.onPrimaryCandidateFound(false, null);
363            return;
364        }
365        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
366            final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
367            if (proxy != null) {
368                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
369                iq.setTo(proxy);
370                iq.query(Namespace.BYTE_STREAMS);
371                account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
372
373                    @Override
374                    public void onIqPacketReceived(Account account, IqPacket packet) {
375                        final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
376                        final String host = streamhost == null ? null : streamhost.getAttribute("host");
377                        final String port = streamhost == null ? null : streamhost.getAttribute("port");
378                        if (host != null && port != null) {
379                            try {
380                                JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
381                                candidate.setHost(host);
382                                candidate.setPort(Integer.parseInt(port));
383                                candidate.setType(JingleCandidate.TYPE_PROXY);
384                                candidate.setJid(proxy);
385                                candidate.setPriority(655360 + (initiator ? 30 : 0));
386                                primaryCandidates.put(account.getJid().asBareJid(), candidate);
387                                listener.onPrimaryCandidateFound(true, candidate);
388                            } catch (final NumberFormatException e) {
389                                listener.onPrimaryCandidateFound(false, null);
390                            }
391                        } else {
392                            listener.onPrimaryCandidateFound(false, null);
393                        }
394                    }
395                });
396            } else {
397                listener.onPrimaryCandidateFound(false, null);
398            }
399
400        } else {
401            listener.onPrimaryCandidateFound(true,
402                    this.primaryCandidates.get(account.getJid().asBareJid()));
403        }
404    }
405
406    public void retractSessionProposal(final Account account, final Jid with) {
407        synchronized (this.rtpSessionProposals) {
408            RtpSessionProposal matchingProposal = null;
409            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
410                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
411                    matchingProposal = proposal;
412                    break;
413                }
414            }
415            if (matchingProposal != null) {
416                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retracting rtp session proposal with " + with);
417                this.rtpSessionProposals.remove(matchingProposal);
418                final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(matchingProposal);
419                writeLogMissedOutgoing(account, matchingProposal.with, matchingProposal.sessionId, null, System.currentTimeMillis());
420                mXmppConnectionService.sendMessagePacket(account, messagePacket);
421            }
422        }
423    }
424
425    public void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
426        synchronized (this.rtpSessionProposals) {
427            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
428                RtpSessionProposal proposal = entry.getKey();
429                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
430                    final DeviceDiscoveryState preexistingState = entry.getValue();
431                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
432                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
433                                account,
434                                with,
435                                proposal.sessionId,
436                                preexistingState.toEndUserState()
437                        );
438                        return;
439                    }
440                }
441            }
442            if (isBusy()) {
443                throw new IllegalStateException("There is already a running RTP session. This should have been caught by the UI");
444            }
445            final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid(), media);
446            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
447            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
448                    account,
449                    proposal.with,
450                    proposal.sessionId,
451                    RtpEndUserState.FINDING_DEVICE
452            );
453            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
454            Log.d(Config.LOGTAG, messagePacket.toString());
455            mXmppConnectionService.sendMessagePacket(account, messagePacket);
456        }
457    }
458
459    public void deliverIbbPacket(Account account, IqPacket packet) {
460        final String sid;
461        final Element payload;
462        if (packet.hasChild("open", Namespace.IBB)) {
463            payload = packet.findChild("open", Namespace.IBB);
464            sid = payload.getAttribute("sid");
465        } else if (packet.hasChild("data", Namespace.IBB)) {
466            payload = packet.findChild("data", Namespace.IBB);
467            sid = payload.getAttribute("sid");
468        } else if (packet.hasChild("close", Namespace.IBB)) {
469            payload = packet.findChild("close", Namespace.IBB);
470            sid = payload.getAttribute("sid");
471        } else {
472            payload = null;
473            sid = null;
474        }
475        if (sid != null) {
476            for (final AbstractJingleConnection connection : this.connections.values()) {
477                if (connection instanceof JingleFileTransferConnection) {
478                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
479                    final JingleTransport transport = fileTransfer.getTransport();
480                    if (transport instanceof JingleInBandTransport) {
481                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
482                        if (inBandTransport.matches(account, sid)) {
483                            inBandTransport.deliverPayload(packet, payload);
484                        }
485                        return;
486                    }
487                }
488            }
489        }
490        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
491        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
492    }
493
494    public void notifyRebound() {
495        for (final AbstractJingleConnection connection : this.connections.values()) {
496            connection.notifyRebound();
497        }
498    }
499
500    public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
501        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
502        final AbstractJingleConnection connection = connections.get(id);
503        if (connection instanceof JingleRtpConnection) {
504            return new WeakReference<>((JingleRtpConnection) connection);
505        }
506        return null;
507    }
508
509    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
510        synchronized (this.rtpSessionProposals) {
511            final RtpSessionProposal sessionProposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
512            final DeviceDiscoveryState currentState = sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
513            if (currentState == null) {
514                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
515                return;
516            }
517            if (currentState == DeviceDiscoveryState.DISCOVERED) {
518                Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
519                return;
520            }
521            this.rtpSessionProposals.put(sessionProposal, target);
522            mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, target.toEndUserState());
523            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
524        }
525    }
526
527    public void rejectRtpSession(final String sessionId) {
528        for (final AbstractJingleConnection connection : this.connections.values()) {
529            if (connection.getId().sessionId.equals(sessionId)) {
530                if (connection instanceof JingleRtpConnection) {
531                    ((JingleRtpConnection) connection).rejectCall();
532                }
533            }
534        }
535    }
536
537    public void endRtpSession(final String sessionId) {
538        for (final AbstractJingleConnection connection : this.connections.values()) {
539            if (connection.getId().sessionId.equals(sessionId)) {
540                if (connection instanceof JingleRtpConnection) {
541                    ((JingleRtpConnection) connection).endCall();
542                }
543            }
544        }
545    }
546
547    public void failProceed(Account account, final Jid with, String sessionId) {
548        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
549        final AbstractJingleConnection existingJingleConnection = connections.get(id);
550        if (existingJingleConnection instanceof JingleRtpConnection) {
551            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
552        }
553    }
554
555    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
556        if (connections.containsValue(connection)) {
557            return;
558        }
559        final IllegalStateException e = new IllegalStateException("JingleConnection has not been registered with connection manager");
560        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
561        throw e;
562    }
563
564    public void endSession(AbstractJingleConnection.Id id, final AbstractJingleConnection.State state) {
565        this.endedSessions.put(PersistableSessionId.of(id), state);
566    }
567
568    private static class PersistableSessionId {
569        private final Jid with;
570        private final String sessionId;
571
572        private PersistableSessionId(Jid with, String sessionId) {
573            this.with = with;
574            this.sessionId = sessionId;
575        }
576
577        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
578            return new PersistableSessionId(id.with, id.sessionId);
579        }
580
581        @Override
582        public boolean equals(Object o) {
583            if (this == o) return true;
584            if (o == null || getClass() != o.getClass()) return false;
585            PersistableSessionId that = (PersistableSessionId) o;
586            return Objects.equal(with, that.with) &&
587                    Objects.equal(sessionId, that.sessionId);
588        }
589
590        @Override
591        public int hashCode() {
592            return Objects.hashCode(with, sessionId);
593        }
594    }
595
596    public enum DeviceDiscoveryState {
597        SEARCHING, DISCOVERED, FAILED;
598
599        public RtpEndUserState toEndUserState() {
600            switch (this) {
601                case SEARCHING:
602                    return RtpEndUserState.FINDING_DEVICE;
603                case DISCOVERED:
604                    return RtpEndUserState.RINGING;
605                default:
606                    return RtpEndUserState.CONNECTIVITY_ERROR;
607            }
608        }
609    }
610
611    public static class RtpSessionProposal {
612        public final Jid with;
613        public final String sessionId;
614        public final Set<Media> media;
615        private final Account account;
616
617        private RtpSessionProposal(Account account, Jid with, String sessionId) {
618            this(account, with, sessionId, Collections.emptySet());
619        }
620
621        private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
622            this.account = account;
623            this.with = with;
624            this.sessionId = sessionId;
625            this.media = media;
626        }
627
628        public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
629            return new RtpSessionProposal(account, with, nextRandomId(), media);
630        }
631
632        @Override
633        public boolean equals(Object o) {
634            if (this == o) return true;
635            if (o == null || getClass() != o.getClass()) return false;
636            RtpSessionProposal proposal = (RtpSessionProposal) o;
637            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
638                    Objects.equal(with, proposal.with) &&
639                    Objects.equal(sessionId, proposal.sessionId);
640        }
641
642        @Override
643        public int hashCode() {
644            return Objects.hashCode(account.getJid(), with, sessionId);
645        }
646    }
647}