JingleRtpConnection.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.os.SystemClock;
   4import android.util.Log;
   5
   6import com.google.common.base.Optional;
   7import com.google.common.base.Preconditions;
   8import com.google.common.base.Strings;
   9import com.google.common.collect.Collections2;
  10import com.google.common.collect.ImmutableList;
  11import com.google.common.collect.ImmutableMap;
  12import com.google.common.collect.Sets;
  13import com.google.common.primitives.Ints;
  14
  15import org.webrtc.EglBase;
  16import org.webrtc.IceCandidate;
  17import org.webrtc.PeerConnection;
  18import org.webrtc.VideoTrack;
  19
  20import java.util.ArrayDeque;
  21import java.util.Arrays;
  22import java.util.Collection;
  23import java.util.Collections;
  24import java.util.List;
  25import java.util.Map;
  26import java.util.Set;
  27
  28import eu.siacs.conversations.Config;
  29import eu.siacs.conversations.entities.Account;
  30import eu.siacs.conversations.entities.Conversation;
  31import eu.siacs.conversations.entities.Conversational;
  32import eu.siacs.conversations.entities.Message;
  33import eu.siacs.conversations.entities.RtpSessionStatus;
  34import eu.siacs.conversations.services.AppRTCAudioManager;
  35import eu.siacs.conversations.xml.Element;
  36import eu.siacs.conversations.xml.Namespace;
  37import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
  38import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
  39import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  40import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  41import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  42import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  43import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  44import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  45import rocks.xmpp.addr.Jid;
  46
  47public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
  48
  49    public static final List<State> STATES_SHOWING_ONGOING_CALL = Arrays.asList(
  50            State.PROCEED,
  51            State.SESSION_INITIALIZED,
  52            State.SESSION_INITIALIZED_PRE_APPROVED,
  53            State.SESSION_ACCEPTED
  54    );
  55
  56    private static final List<State> TERMINATED = Arrays.asList(
  57            State.TERMINATED_SUCCESS,
  58            State.TERMINATED_DECLINED_OR_BUSY,
  59            State.TERMINATED_CONNECTIVITY_ERROR,
  60            State.TERMINATED_CANCEL_OR_TIMEOUT,
  61            State.TERMINATED_APPLICATION_FAILURE
  62    );
  63
  64    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
  65
  66    static {
  67        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
  68        transitionBuilder.put(State.NULL, ImmutableList.of(
  69                State.PROPOSED,
  70                State.SESSION_INITIALIZED,
  71                State.TERMINATED_APPLICATION_FAILURE
  72        ));
  73        transitionBuilder.put(State.PROPOSED, ImmutableList.of(
  74                State.ACCEPTED,
  75                State.PROCEED,
  76                State.REJECTED,
  77                State.RETRACTED,
  78                State.TERMINATED_APPLICATION_FAILURE,
  79                State.TERMINATED_CONNECTIVITY_ERROR //only used when the xmpp connection rebinds
  80        ));
  81        transitionBuilder.put(State.PROCEED, ImmutableList.of(
  82                State.SESSION_INITIALIZED_PRE_APPROVED,
  83                State.TERMINATED_SUCCESS,
  84                State.TERMINATED_APPLICATION_FAILURE,
  85                State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
  86        ));
  87        transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
  88                State.SESSION_ACCEPTED,
  89                State.TERMINATED_SUCCESS,
  90                State.TERMINATED_DECLINED_OR_BUSY,
  91                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
  92                State.TERMINATED_CANCEL_OR_TIMEOUT,
  93                State.TERMINATED_APPLICATION_FAILURE
  94        ));
  95        transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
  96                State.SESSION_ACCEPTED,
  97                State.TERMINATED_SUCCESS,
  98                State.TERMINATED_DECLINED_OR_BUSY,
  99                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 100                State.TERMINATED_CANCEL_OR_TIMEOUT,
 101                State.TERMINATED_APPLICATION_FAILURE
 102        ));
 103        transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
 104                State.TERMINATED_SUCCESS,
 105                State.TERMINATED_DECLINED_OR_BUSY,
 106                State.TERMINATED_CONNECTIVITY_ERROR,
 107                State.TERMINATED_CANCEL_OR_TIMEOUT,
 108                State.TERMINATED_APPLICATION_FAILURE
 109        ));
 110        VALID_TRANSITIONS = transitionBuilder.build();
 111    }
 112
 113    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
 114    private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
 115    private final Message message;
 116    private State state = State.NULL;
 117    private Set<Media> proposedMedia;
 118    private RtpContentMap initiatorRtpContentMap;
 119    private RtpContentMap responderRtpContentMap;
 120    private long rtpConnectionStarted = 0; //time of 'connected'
 121
 122    JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
 123        super(jingleConnectionManager, id, initiator);
 124        final Conversation conversation = jingleConnectionManager.getXmppConnectionService().findOrCreateConversation(
 125                id.account,
 126                id.with.asBareJid(),
 127                false,
 128                false
 129        );
 130        this.message = new Message(
 131                conversation,
 132                isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
 133                Message.TYPE_RTP_SESSION,
 134                id.sessionId
 135        );
 136    }
 137
 138    private static State reasonToState(Reason reason) {
 139        switch (reason) {
 140            case SUCCESS:
 141                return State.TERMINATED_SUCCESS;
 142            case DECLINE:
 143            case BUSY:
 144                return State.TERMINATED_DECLINED_OR_BUSY;
 145            case CANCEL:
 146            case TIMEOUT:
 147                return State.TERMINATED_CANCEL_OR_TIMEOUT;
 148            case FAILED_APPLICATION:
 149            case SECURITY_ERROR:
 150            case UNSUPPORTED_TRANSPORTS:
 151            case UNSUPPORTED_APPLICATIONS:
 152                return State.TERMINATED_APPLICATION_FAILURE;
 153            default:
 154                return State.TERMINATED_CONNECTIVITY_ERROR;
 155        }
 156    }
 157
 158    @Override
 159    synchronized void deliverPacket(final JinglePacket jinglePacket) {
 160        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
 161        switch (jinglePacket.getAction()) {
 162            case SESSION_INITIATE:
 163                receiveSessionInitiate(jinglePacket);
 164                break;
 165            case TRANSPORT_INFO:
 166                receiveTransportInfo(jinglePacket);
 167                break;
 168            case SESSION_ACCEPT:
 169                receiveSessionAccept(jinglePacket);
 170                break;
 171            case SESSION_TERMINATE:
 172                receiveSessionTerminate(jinglePacket);
 173                break;
 174            default:
 175                respondOk(jinglePacket);
 176                Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
 177                break;
 178        }
 179    }
 180
 181    @Override
 182    synchronized void notifyRebound() {
 183        if (TERMINATED.contains(this.state)) {
 184            return;
 185        }
 186        webRTCWrapper.close();
 187        if (!isInitiator() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
 188            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 189        }
 190        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 191            //we might have already changed resources (full jid) at this point; so this might not even reach the other party
 192            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 193        } else {
 194            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 195            finish();
 196        }
 197    }
 198
 199    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
 200        respondOk(jinglePacket);
 201        final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
 202        final State previous = this.state;
 203        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + wrapper.reason + "(" + Strings.nullToEmpty(wrapper.text) + ") while in state " + previous);
 204        if (TERMINATED.contains(previous)) {
 205            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring session terminate because already in " + previous);
 206            return;
 207        }
 208        webRTCWrapper.close();
 209        final State target = reasonToState(wrapper.reason);
 210        transitionOrThrow(target);
 211        writeLogMessage(target);
 212        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
 213            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 214        }
 215        finish();
 216    }
 217
 218    private void receiveTransportInfo(final JinglePacket jinglePacket) {
 219        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 220            respondOk(jinglePacket);
 221            final RtpContentMap contentMap;
 222            try {
 223                contentMap = RtpContentMap.of(jinglePacket);
 224            } catch (IllegalArgumentException | NullPointerException e) {
 225                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
 226                return;
 227            }
 228            final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
 229            final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
 230            final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
 231            if (identificationTags.size() == 0) {
 232                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
 233            }
 234            for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
 235                final String ufrag = content.getValue().transport.getAttribute("ufrag");
 236                for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
 237                    final String sdp;
 238                    try {
 239                        sdp = candidate.toSdpAttribute(ufrag);
 240                    } catch (IllegalArgumentException e) {
 241                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring invalid ICE candidate " + e.getMessage());
 242                        continue;
 243                    }
 244                    final String sdpMid = content.getKey();
 245                    final int mLineIndex = identificationTags.indexOf(sdpMid);
 246                    final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
 247                    if (isInState(State.SESSION_ACCEPTED)) {
 248                        Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
 249                        this.webRTCWrapper.addIceCandidate(iceCandidate);
 250                    } else {
 251                        this.pendingIceCandidates.offer(iceCandidate);
 252                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": put ICE candidate on backlog");
 253                    }
 254                }
 255            }
 256        } else {
 257            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
 258            terminateWithOutOfOrder(jinglePacket);
 259        }
 260    }
 261
 262    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
 263        if (isInitiator()) {
 264            Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
 265            terminateWithOutOfOrder(jinglePacket);
 266            return;
 267        }
 268        final RtpContentMap contentMap;
 269        try {
 270            contentMap = RtpContentMap.of(jinglePacket);
 271            contentMap.requireContentDescriptions();
 272            contentMap.requireDTLSFingerprint();
 273        } catch (final RuntimeException e) {
 274            respondOk(jinglePacket);
 275            sendSessionTerminate(Reason.of(e), e.getMessage());
 276            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
 277            return;
 278        }
 279        Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
 280        final State target;
 281        if (this.state == State.PROCEED) {
 282            Preconditions.checkState(
 283                    proposedMedia != null && proposedMedia.size() > 0,
 284                    "proposed media must be set when processing pre-approved session-initiate"
 285            );
 286            if (!this.proposedMedia.equals(contentMap.getMedia())) {
 287                sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 288                        "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
 289                        this.proposedMedia,
 290                        contentMap.getMedia()
 291                ));
 292                return;
 293            }
 294            target = State.SESSION_INITIALIZED_PRE_APPROVED;
 295        } else {
 296            target = State.SESSION_INITIALIZED;
 297        }
 298        if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
 299            respondOk(jinglePacket);
 300            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
 301                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
 302                sendSessionAccept();
 303            } else {
 304                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
 305                startRinging();
 306            }
 307        } else {
 308            Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
 309            terminateWithOutOfOrder(jinglePacket);
 310        }
 311    }
 312
 313    private void receiveSessionAccept(final JinglePacket jinglePacket) {
 314        if (!isInitiator()) {
 315            Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
 316            terminateWithOutOfOrder(jinglePacket);
 317            return;
 318        }
 319        final RtpContentMap contentMap;
 320        try {
 321            contentMap = RtpContentMap.of(jinglePacket);
 322            contentMap.requireContentDescriptions();
 323            contentMap.requireDTLSFingerprint();
 324        } catch (final RuntimeException e) {
 325            respondOk(jinglePacket);
 326            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
 327            webRTCWrapper.close();
 328            sendSessionTerminate(Reason.of(e), e.getMessage());
 329            return;
 330        }
 331        final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
 332        if (!initiatorMedia.equals(contentMap.getMedia())) {
 333            sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 334                    "Your session-included included media %s but our session-initiate was %s",
 335                    this.proposedMedia,
 336                    contentMap.getMedia()
 337            ));
 338            return;
 339        }
 340        Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
 341        if (transition(State.SESSION_ACCEPTED)) {
 342            respondOk(jinglePacket);
 343            receiveSessionAccept(contentMap);
 344        } else {
 345            Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
 346            respondOk(jinglePacket);
 347        }
 348    }
 349
 350    private void receiveSessionAccept(final RtpContentMap contentMap) {
 351        this.responderRtpContentMap = contentMap;
 352        final SessionDescription sessionDescription;
 353        try {
 354            sessionDescription = SessionDescription.of(contentMap);
 355        } catch (final IllegalArgumentException | NullPointerException e) {
 356            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
 357            webRTCWrapper.close();
 358            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 359            return;
 360        }
 361        org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
 362                org.webrtc.SessionDescription.Type.ANSWER,
 363                sessionDescription.toString()
 364        );
 365        try {
 366            this.webRTCWrapper.setRemoteDescription(answer).get();
 367        } catch (Exception e) {
 368            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", e);
 369            webRTCWrapper.close();
 370            sendSessionTerminate(Reason.FAILED_APPLICATION);
 371        }
 372    }
 373
 374    private void sendSessionAccept() {
 375        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
 376        if (rtpContentMap == null) {
 377            throw new IllegalStateException("initiator RTP Content Map has not been set");
 378        }
 379        final SessionDescription offer;
 380        try {
 381            offer = SessionDescription.of(rtpContentMap);
 382        } catch (final IllegalArgumentException | NullPointerException e) {
 383            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
 384            webRTCWrapper.close();
 385            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 386            return;
 387        }
 388        sendSessionAccept(rtpContentMap.getMedia(), offer);
 389    }
 390
 391    private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
 392        discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
 393    }
 394
 395    private synchronized void sendSessionAccept(final Set<Media> media, final SessionDescription offer, final List<PeerConnection.IceServer> iceServers) {
 396        if (TERMINATED.contains(this.state)) {
 397            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 398            return;
 399        }
 400        try {
 401            setupWebRTC(media, iceServers);
 402        } catch (WebRTCWrapper.InitializationException e) {
 403            sendSessionTerminate(Reason.FAILED_APPLICATION);
 404            return;
 405        }
 406        final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
 407                org.webrtc.SessionDescription.Type.OFFER,
 408                offer.toString()
 409        );
 410        try {
 411            this.webRTCWrapper.setRemoteDescription(sdp).get();
 412            addIceCandidatesFromBlackLog();
 413            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
 414            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 415            final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
 416            sendSessionAccept(respondingRtpContentMap);
 417            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
 418        } catch (Exception e) {
 419            Log.d(Config.LOGTAG, "unable to send session accept", e);
 420
 421        }
 422    }
 423
 424    private void addIceCandidatesFromBlackLog() {
 425        while (!this.pendingIceCandidates.isEmpty()) {
 426            final IceCandidate iceCandidate = this.pendingIceCandidates.poll();
 427            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added ICE candidate from back log " + iceCandidate);
 428            this.webRTCWrapper.addIceCandidate(iceCandidate);
 429        }
 430    }
 431
 432    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
 433        this.responderRtpContentMap = rtpContentMap;
 434        this.transitionOrThrow(State.SESSION_ACCEPTED);
 435        final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
 436        Log.d(Config.LOGTAG, sessionAccept.toString());
 437        send(sessionAccept);
 438    }
 439
 440    synchronized void deliveryMessage(final Jid from, final Element message, final String serverMessageId, final long timestamp) {
 441        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
 442        switch (message.getName()) {
 443            case "propose":
 444                receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
 445                break;
 446            case "proceed":
 447                receiveProceed(from, serverMessageId, timestamp);
 448                break;
 449            case "retract":
 450                receiveRetract(from, serverMessageId, timestamp);
 451                break;
 452            case "reject":
 453                receiveReject(from, serverMessageId, timestamp);
 454                break;
 455            case "accept":
 456                receiveAccept(from, serverMessageId, timestamp);
 457                break;
 458            default:
 459                break;
 460        }
 461    }
 462
 463    void deliverFailedProceed() {
 464        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
 465        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
 466            webRTCWrapper.close();
 467            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
 468            this.finish();
 469        }
 470    }
 471
 472    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
 473        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 474        if (originatedFromMyself) {
 475            if (transition(State.ACCEPTED)) {
 476                if (serverMsgId != null) {
 477                    this.message.setServerMsgId(serverMsgId);
 478                }
 479                this.message.setTime(timestamp);
 480                this.message.setCarbon(true); //indicate that call was accepted on other device
 481                this.writeLogMessageSuccess(0);
 482                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 483                this.finish();
 484            } else {
 485                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
 486            }
 487        } else {
 488            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
 489        }
 490    }
 491
 492    private void receiveReject(Jid from, String serverMsgId, long timestamp) {
 493        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 494        //reject from another one of my clients
 495        if (originatedFromMyself) {
 496            if (transition(State.REJECTED)) {
 497                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 498                this.finish();
 499                if (serverMsgId != null) {
 500                    this.message.setServerMsgId(serverMsgId);
 501                }
 502                this.message.setTime(timestamp);
 503                this.message.setCarbon(true); //indicate that call was rejected on other device
 504                writeLogMessageMissed();
 505            } else {
 506                Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
 507            }
 508        } else {
 509            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 510        }
 511    }
 512
 513    private void receivePropose(final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
 514        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 515        if (originatedFromMyself) {
 516            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
 517        } else if (transition(State.PROPOSED, () -> {
 518            final Collection<RtpDescription> descriptions = Collections2.transform(
 519                    Collections2.filter(propose.getDescriptions(), d -> d instanceof RtpDescription),
 520                    input -> (RtpDescription) input
 521            );
 522            final Collection<Media> media = Collections2.transform(descriptions, RtpDescription::getMedia);
 523            Preconditions.checkState(!media.contains(Media.UNKNOWN), "RTP descriptions contain unknown media");
 524            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session proposal from " + from + " for " + media);
 525            this.proposedMedia = Sets.newHashSet(media);
 526        })) {
 527            if (serverMsgId != null) {
 528                this.message.setServerMsgId(serverMsgId);
 529            }
 530            this.message.setTime(timestamp);
 531            startRinging();
 532        } else {
 533            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
 534        }
 535    }
 536
 537    private void startRinging() {
 538        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
 539        xmppConnectionService.getNotificationService().showIncomingCallNotification(id, getMedia());
 540    }
 541
 542    private void receiveProceed(final Jid from, final String serverMsgId, final long timestamp) {
 543        final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
 544        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
 545        if (from.equals(id.with)) {
 546            if (isInitiator()) {
 547                if (transition(State.PROCEED)) {
 548                    if (serverMsgId != null) {
 549                        this.message.setServerMsgId(serverMsgId);
 550                    }
 551                    this.message.setTime(timestamp);
 552                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
 553                } else {
 554                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
 555                }
 556            } else {
 557                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
 558            }
 559        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
 560            if (transition(State.ACCEPTED)) {
 561                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
 562                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 563                this.finish();
 564            }
 565        } else {
 566            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
 567        }
 568    }
 569
 570    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
 571        if (from.equals(id.with)) {
 572            if (transition(State.RETRACTED)) {
 573                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 574                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
 575                if (serverMsgId != null) {
 576                    this.message.setServerMsgId(serverMsgId);
 577                }
 578                this.message.setTime(timestamp);
 579                writeLogMessageMissed();
 580                finish();
 581            } else {
 582                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
 583            }
 584        } else {
 585            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
 586        }
 587    }
 588
 589    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
 590        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
 591        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
 592    }
 593
 594    private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
 595        if (TERMINATED.contains(this.state)) {
 596            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 597            return;
 598        }
 599        try {
 600            setupWebRTC(media, iceServers);
 601        } catch (WebRTCWrapper.InitializationException e) {
 602            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize webrtc");
 603            transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 604            return;
 605        }
 606        try {
 607            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
 608            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 609            final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
 610            sendSessionInitiate(rtpContentMap, targetState);
 611            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
 612        } catch (final Exception e) {
 613            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", e);
 614            webRTCWrapper.close();
 615            if (isInState(targetState)) {
 616                sendSessionTerminate(Reason.FAILED_APPLICATION);
 617            } else {
 618                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 619            }
 620        }
 621    }
 622
 623    private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
 624        this.initiatorRtpContentMap = rtpContentMap;
 625        this.transitionOrThrow(targetState);
 626        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
 627        send(sessionInitiate);
 628    }
 629
 630    private void sendSessionTerminate(final Reason reason) {
 631        sendSessionTerminate(reason, null);
 632    }
 633
 634    private void sendSessionTerminate(final Reason reason, final String text) {
 635        final State target = reasonToState(reason);
 636        transitionOrThrow(target);
 637        writeLogMessage(target);
 638        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 639        jinglePacket.setReason(reason, text);
 640        Log.d(Config.LOGTAG, jinglePacket.toString());
 641        send(jinglePacket);
 642        finish();
 643    }
 644
 645    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 646        final RtpContentMap transportInfo;
 647        try {
 648            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 649            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 650        } catch (Exception e) {
 651            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 652            return;
 653        }
 654        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 655        send(jinglePacket);
 656    }
 657
 658    private void send(final JinglePacket jinglePacket) {
 659        jinglePacket.setTo(id.with);
 660        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
 661    }
 662
 663    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
 664        if (response.getType() == IqPacket.TYPE.ERROR) {
 665            final String errorCondition = response.getErrorCondition();
 666            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 667            if (TERMINATED.contains(this.state)) {
 668                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 669                return;
 670            }
 671            this.webRTCWrapper.close();
 672            final State target;
 673            if (Arrays.asList(
 674                    "service-unavailable",
 675                    "recipient-unavailable",
 676                    "remote-server-not-found",
 677                    "remote-server-timeout"
 678            ).contains(errorCondition)) {
 679                target = State.TERMINATED_CONNECTIVITY_ERROR;
 680            } else {
 681                target = State.TERMINATED_APPLICATION_FAILURE;
 682            }
 683            if (transition(target)) {
 684                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminated session with " + id.with);
 685            } else {
 686                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not transitioning because already at state=" + this.state);
 687            }
 688        } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 689            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 690            if (TERMINATED.contains(this.state)) {
 691                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 692                return;
 693            }
 694            this.webRTCWrapper.close();
 695            transition(State.TERMINATED_CONNECTIVITY_ERROR);
 696            this.finish();
 697        }
 698    }
 699
 700    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 701        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 702        this.webRTCWrapper.close();
 703        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 704        respondWithOutOfOrder(jinglePacket);
 705        this.finish();
 706    }
 707
 708    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
 709        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
 710    }
 711
 712    private void respondOk(final JinglePacket jinglePacket) {
 713        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
 714    }
 715
 716    public RtpEndUserState getEndUserState() {
 717        switch (this.state) {
 718            case PROPOSED:
 719            case SESSION_INITIALIZED:
 720                if (isInitiator()) {
 721                    return RtpEndUserState.RINGING;
 722                } else {
 723                    return RtpEndUserState.INCOMING_CALL;
 724                }
 725            case PROCEED:
 726                if (isInitiator()) {
 727                    return RtpEndUserState.RINGING;
 728                } else {
 729                    return RtpEndUserState.ACCEPTING_CALL;
 730                }
 731            case SESSION_INITIALIZED_PRE_APPROVED:
 732                if (isInitiator()) {
 733                    return RtpEndUserState.RINGING;
 734                } else {
 735                    return RtpEndUserState.CONNECTING;
 736                }
 737            case SESSION_ACCEPTED:
 738                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
 739                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
 740                    return RtpEndUserState.CONNECTED;
 741                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
 742                    return RtpEndUserState.CONNECTING;
 743                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
 744                    return RtpEndUserState.ENDING_CALL;
 745                } else {
 746                    return RtpEndUserState.CONNECTIVITY_ERROR;
 747                }
 748            case REJECTED:
 749            case TERMINATED_DECLINED_OR_BUSY:
 750                if (isInitiator()) {
 751                    return RtpEndUserState.DECLINED_OR_BUSY;
 752                } else {
 753                    return RtpEndUserState.ENDED;
 754                }
 755            case TERMINATED_SUCCESS:
 756            case ACCEPTED:
 757            case RETRACTED:
 758            case TERMINATED_CANCEL_OR_TIMEOUT:
 759                return RtpEndUserState.ENDED;
 760            case TERMINATED_CONNECTIVITY_ERROR:
 761                return RtpEndUserState.CONNECTIVITY_ERROR;
 762            case TERMINATED_APPLICATION_FAILURE:
 763                return RtpEndUserState.APPLICATION_ERROR;
 764        }
 765        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
 766    }
 767
 768    public Set<Media> getMedia() {
 769        if (isInState(State.NULL)) {
 770            throw new IllegalStateException("RTP connection has not been initialized yet");
 771        }
 772        if (isInState(State.PROPOSED, State.PROCEED)) {
 773            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 774        }
 775        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
 776        if (initiatorContentMap != null) {
 777            return initiatorContentMap.getMedia();
 778        } else {
 779            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 780        }
 781    }
 782
 783
 784    public synchronized void acceptCall() {
 785        switch (this.state) {
 786            case PROPOSED:
 787                acceptCallFromProposed();
 788                break;
 789            case SESSION_INITIALIZED:
 790                acceptCallFromSessionInitialized();
 791                break;
 792            case ACCEPTED:
 793                Log.w(Config.LOGTAG,id.account.getJid().asBareJid()+": the call has already been accepted  with another client. UI was just lagging behind");
 794                break;
 795            case PROCEED:
 796            case SESSION_ACCEPTED:
 797                Log.w(Config.LOGTAG,id.account.getJid().asBareJid()+": the call has already been accepted. user probably double tapped the UI");
 798                break;
 799            default:
 800                throw new IllegalStateException("Can not accept call from " + this.state);
 801        }
 802    }
 803
 804    public synchronized void rejectCall() {
 805        switch (this.state) {
 806            case PROPOSED:
 807                rejectCallFromProposed();
 808                break;
 809            case SESSION_INITIALIZED:
 810                rejectCallFromSessionInitiate();
 811                break;
 812            default:
 813                throw new IllegalStateException("Can not reject call from " + this.state);
 814        }
 815    }
 816
 817    public synchronized void endCall() {
 818        if (TERMINATED.contains(this.state)) {
 819            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
 820            return;
 821        }
 822        if (isInState(State.PROPOSED) && !isInitiator()) {
 823            rejectCallFromProposed();
 824            return;
 825        }
 826        if (isInState(State.PROCEED)) {
 827            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
 828            this.jingleConnectionManager.endSession(id, State.TERMINATED_SUCCESS);
 829            this.webRTCWrapper.close();
 830            this.finish();
 831            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
 832            return;
 833        }
 834        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
 835            this.webRTCWrapper.close();
 836            sendSessionTerminate(Reason.CANCEL);
 837            return;
 838        }
 839        if (isInState(State.SESSION_INITIALIZED)) {
 840            rejectCallFromSessionInitiate();
 841            return;
 842        }
 843        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 844            this.webRTCWrapper.close();
 845            sendSessionTerminate(Reason.SUCCESS);
 846            return;
 847        }
 848        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
 849            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
 850            return;
 851        }
 852        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
 853    }
 854
 855    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
 856        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
 857        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
 858        if (media.contains(Media.VIDEO)) {
 859            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
 860        } else {
 861            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
 862        }
 863        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
 864        this.webRTCWrapper.initializePeerConnection(media, iceServers);
 865    }
 866
 867    private void acceptCallFromProposed() {
 868        transitionOrThrow(State.PROCEED);
 869        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 870        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
 871        this.sendJingleMessage("proceed");
 872    }
 873
 874    private void rejectCallFromProposed() {
 875        transitionOrThrow(State.REJECTED);
 876        writeLogMessageMissed();
 877        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 878        this.sendJingleMessage("reject");
 879        finish();
 880    }
 881
 882    private void rejectCallFromSessionInitiate() {
 883        webRTCWrapper.close();
 884        sendSessionTerminate(Reason.DECLINE);
 885        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 886    }
 887
 888    private void sendJingleMessage(final String action) {
 889        sendJingleMessage(action, id.with);
 890    }
 891
 892    private void sendJingleMessage(final String action, final Jid to) {
 893        final MessagePacket messagePacket = new MessagePacket();
 894        if ("proceed".equals(action)) {
 895            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
 896        }
 897        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
 898        messagePacket.setTo(to);
 899        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
 900        messagePacket.addChild("store", "urn:xmpp:hints");
 901        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
 902    }
 903
 904    private void acceptCallFromSessionInitialized() {
 905        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 906        sendSessionAccept();
 907    }
 908
 909    private synchronized boolean isInState(State... state) {
 910        return Arrays.asList(state).contains(this.state);
 911    }
 912
 913    private boolean transition(final State target) {
 914        return transition(target, null);
 915    }
 916
 917    private synchronized boolean transition(final State target, final Runnable runnable) {
 918        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
 919        if (validTransitions != null && validTransitions.contains(target)) {
 920            this.state = target;
 921            if (runnable != null) {
 922                runnable.run();
 923            }
 924            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
 925            updateEndUserState();
 926            updateOngoingCallNotification();
 927            return true;
 928        } else {
 929            return false;
 930        }
 931    }
 932
 933    public void transitionOrThrow(final State target) {
 934        if (!transition(target)) {
 935            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
 936        }
 937    }
 938
 939    @Override
 940    public void onIceCandidate(final IceCandidate iceCandidate) {
 941        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
 942        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
 943        sendTransportInfo(iceCandidate.sdpMid, candidate);
 944    }
 945
 946    @Override
 947    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
 948        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
 949        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
 950            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
 951        }
 952        //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
 953        //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
 954        //as there is no content-replace
 955        if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
 956            if (TERMINATED.contains(this.state)) {
 957                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
 958                return;
 959            }
 960            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
 961        } else {
 962            updateEndUserState();
 963        }
 964    }
 965
 966    private void closeWebRTCSessionAfterFailedConnection() {
 967        this.webRTCWrapper.close();
 968        synchronized (this) {
 969            if (TERMINATED.contains(state)) {
 970                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
 971                return;
 972            }
 973            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 974        }
 975    }
 976
 977    public AppRTCAudioManager getAudioManager() {
 978        return webRTCWrapper.getAudioManager();
 979    }
 980
 981    public boolean isMicrophoneEnabled() {
 982        return webRTCWrapper.isMicrophoneEnabled();
 983    }
 984
 985    public void setMicrophoneEnabled(final boolean enabled) {
 986        webRTCWrapper.setMicrophoneEnabled(enabled);
 987    }
 988
 989    public boolean isVideoEnabled() {
 990        return webRTCWrapper.isVideoEnabled();
 991    }
 992
 993    public void setVideoEnabled(final boolean enabled) {
 994        webRTCWrapper.setVideoEnabled(enabled);
 995    }
 996
 997    @Override
 998    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
 999        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1000    }
1001
1002    private void updateEndUserState() {
1003        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
1004    }
1005
1006    private void updateOngoingCallNotification() {
1007        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1008            xmppConnectionService.setOngoingCall(id, getMedia());
1009        } else {
1010            xmppConnectionService.removeOngoingCall();
1011        }
1012    }
1013
1014    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1015        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1016            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1017            request.setTo(Jid.of(id.account.getJid().getDomain()));
1018            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1019            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1020                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1021                if (response.getType() == IqPacket.TYPE.RESULT) {
1022                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1023                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1024                    for (final Element child : children) {
1025                        if ("service".equals(child.getName())) {
1026                            final String type = child.getAttribute("type");
1027                            final String host = child.getAttribute("host");
1028                            final String sport = child.getAttribute("port");
1029                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1030                            final String transport = child.getAttribute("transport");
1031                            final String username = child.getAttribute("username");
1032                            final String password = child.getAttribute("password");
1033                            if (Strings.isNullOrEmpty(host) || port == null) {
1034                                continue;
1035                            }
1036                            if (port < 0 || port > 65535) {
1037                                continue;
1038                            }
1039                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1040                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1041                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1042                                    continue;
1043                                }
1044                                //TODO wrap ipv6 addresses
1045                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
1046                                if (username != null && password != null) {
1047                                    iceServerBuilder.setUsername(username);
1048                                    iceServerBuilder.setPassword(password);
1049                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1050                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1051                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1052                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1053                                    continue;
1054                                }
1055                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1056                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1057                                listBuilder.add(iceServer);
1058                            }
1059                        }
1060                    }
1061                }
1062                List<PeerConnection.IceServer> iceServers = listBuilder.build();
1063                if (iceServers.size() == 0) {
1064                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1065                }
1066                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1067            });
1068        } else {
1069            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1070            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1071        }
1072    }
1073
1074    private void finish() {
1075        this.webRTCWrapper.verifyClosed();
1076        this.jingleConnectionManager.finishConnection(this);
1077    }
1078
1079    private void writeLogMessage(final State state) {
1080        final long started = this.rtpConnectionStarted;
1081        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1082        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1083            writeLogMessageSuccess(duration);
1084        } else {
1085            writeLogMessageMissed();
1086        }
1087    }
1088
1089    private void writeLogMessageSuccess(final long duration) {
1090        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1091        this.writeMessage();
1092    }
1093
1094    private void writeLogMessageMissed() {
1095        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1096        this.writeMessage();
1097    }
1098
1099    private void writeMessage() {
1100        final Conversational conversational = message.getConversation();
1101        if (conversational instanceof Conversation) {
1102            ((Conversation) conversational).add(this.message);
1103            xmppConnectionService.databaseBackend.createMessage(message);
1104            xmppConnectionService.updateConversationUi();
1105        } else {
1106            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1107        }
1108    }
1109
1110    public State getState() {
1111        return this.state;
1112    }
1113
1114    public Optional<VideoTrack> geLocalVideoTrack() {
1115        return webRTCWrapper.getLocalVideoTrack();
1116    }
1117
1118    public Optional<VideoTrack> getRemoteVideoTrack() {
1119        return webRTCWrapper.getRemoteVideoTrack();
1120    }
1121
1122
1123    public EglBase.Context getEglBaseContext() {
1124        return webRTCWrapper.getEglBaseContext();
1125    }
1126
1127    public void setProposedMedia(final Set<Media> media) {
1128        this.proposedMedia = media;
1129    }
1130
1131    private interface OnIceServersDiscovered {
1132        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1133    }
1134}