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