JingleRtpConnection.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import android.util.Log;
  4
  5import com.google.common.collect.ImmutableList;
  6import com.google.common.collect.ImmutableMap;
  7
  8import org.webrtc.IceCandidate;
  9import org.webrtc.PeerConnection;
 10
 11import java.util.ArrayDeque;
 12import java.util.Arrays;
 13import java.util.Collection;
 14import java.util.Collections;
 15import java.util.List;
 16import java.util.Map;
 17
 18import eu.siacs.conversations.Config;
 19import eu.siacs.conversations.entities.Account;
 20import eu.siacs.conversations.xml.Element;
 21import eu.siacs.conversations.xml.Namespace;
 22import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 23import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
 24import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
 25import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 26import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 27import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 28import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 29import rocks.xmpp.addr.Jid;
 30
 31public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
 32
 33    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
 34
 35    static {
 36        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
 37        transitionBuilder.put(State.NULL, ImmutableList.of(State.PROPOSED, State.SESSION_INITIALIZED));
 38        transitionBuilder.put(State.PROPOSED, ImmutableList.of(State.ACCEPTED, State.PROCEED, State.REJECTED, State.RETRACTED));
 39        transitionBuilder.put(State.PROCEED, ImmutableList.of(State.SESSION_INITIALIZED_PRE_APPROVED));
 40        transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(State.SESSION_ACCEPTED, State.TERMINATED_CANCEL_OR_TIMEOUT));
 41        transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(State.SESSION_ACCEPTED, State.TERMINATED_CANCEL_OR_TIMEOUT));
 42        transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(State.TERMINATED_SUCCESS, State.TERMINATED_CONNECTIVITY_ERROR));
 43        VALID_TRANSITIONS = transitionBuilder.build();
 44    }
 45
 46    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
 47    private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
 48    private State state = State.NULL;
 49    private RtpContentMap initiatorRtpContentMap;
 50    private RtpContentMap responderRtpContentMap;
 51
 52
 53    public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
 54        super(jingleConnectionManager, id, initiator);
 55    }
 56
 57    private static State reasonToState(Reason reason) {
 58        switch (reason) {
 59            case SUCCESS:
 60                return State.TERMINATED_SUCCESS;
 61            case DECLINE:
 62            case BUSY:
 63                return State.TERMINATED_DECLINED_OR_BUSY;
 64            case CANCEL:
 65            case TIMEOUT:
 66                return State.TERMINATED_CANCEL_OR_TIMEOUT;
 67            default:
 68                return State.TERMINATED_CONNECTIVITY_ERROR;
 69        }
 70    }
 71
 72    @Override
 73    void deliverPacket(final JinglePacket jinglePacket) {
 74        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
 75        switch (jinglePacket.getAction()) {
 76            case SESSION_INITIATE:
 77                receiveSessionInitiate(jinglePacket);
 78                break;
 79            case TRANSPORT_INFO:
 80                receiveTransportInfo(jinglePacket);
 81                break;
 82            case SESSION_ACCEPT:
 83                receiveSessionAccept(jinglePacket);
 84                break;
 85            case SESSION_TERMINATE:
 86                receiveSessionTerminate(jinglePacket);
 87                break;
 88            default:
 89                Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
 90                break;
 91        }
 92    }
 93
 94    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
 95        final Reason reason = jinglePacket.getReason();
 96        final State previous = this.state;
 97        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + reason + " while in state " + previous);
 98        webRTCWrapper.close();
 99        transitionOrThrow(reasonToState(reason));
100        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
101            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
102        }
103        jingleConnectionManager.finishConnection(this);
104    }
105
106    private void receiveTransportInfo(final JinglePacket jinglePacket) {
107        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
108            final RtpContentMap contentMap;
109            try {
110                contentMap = RtpContentMap.of(jinglePacket);
111            } catch (IllegalArgumentException | NullPointerException e) {
112                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
113                return;
114            }
115            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
116            final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
117            final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
118            if (identificationTags.size() == 0) {
119                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
120            }
121            for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
122                final String ufrag = content.getValue().transport.getAttribute("ufrag");
123                for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
124                    final String sdp = candidate.toSdpAttribute(ufrag);
125                    final String sdpMid = content.getKey();
126                    final int mLineIndex = identificationTags.indexOf(sdpMid);
127                    final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
128                    Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
129                    if (isInState(State.SESSION_ACCEPTED)) {
130                        this.webRTCWrapper.addIceCandidate(iceCandidate);
131                    } else {
132                        this.pendingIceCandidates.push(iceCandidate);
133                    }
134                }
135            }
136        } else {
137            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
138        }
139    }
140
141    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
142        if (isInitiator()) {
143            Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
144            //TODO respond with out-of-order
145            return;
146        }
147        final RtpContentMap contentMap;
148        try {
149            contentMap = RtpContentMap.of(jinglePacket);
150            contentMap.requireContentDescriptions();
151        } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
152            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
153            return;
154        }
155        Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
156        final State target;
157        if (this.state == State.PROCEED) {
158            target = State.SESSION_INITIALIZED_PRE_APPROVED;
159        } else {
160            target = State.SESSION_INITIALIZED;
161        }
162        if (transition(target)) {
163            this.initiatorRtpContentMap = contentMap;
164            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
165                Log.d(Config.LOGTAG, "automatically accepting");
166                sendSessionAccept();
167            } else {
168                Log.d(Config.LOGTAG, "start ringing");
169                //TODO start ringing
170            }
171        } else {
172            Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
173        }
174    }
175
176    private void receiveSessionAccept(final JinglePacket jinglePacket) {
177        if (!isInitiator()) {
178            Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
179            //TODO respond with out-of-order
180            return;
181        }
182        final RtpContentMap contentMap;
183        try {
184            contentMap = RtpContentMap.of(jinglePacket);
185            contentMap.requireContentDescriptions();
186        } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
187            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
188            return;
189        }
190        Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
191        if (transition(State.SESSION_ACCEPTED)) {
192            receiveSessionAccept(contentMap);
193        } else {
194            Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
195            //TODO out-of-order
196        }
197    }
198
199    private void receiveSessionAccept(final RtpContentMap contentMap) {
200        this.responderRtpContentMap = contentMap;
201        org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
202                org.webrtc.SessionDescription.Type.ANSWER,
203                SessionDescription.of(contentMap).toString()
204        );
205        try {
206            this.webRTCWrapper.setRemoteDescription(answer).get();
207        } catch (Exception e) {
208            Log.d(Config.LOGTAG, "unable to receive session accept", e);
209        }
210    }
211
212    private void sendSessionAccept() {
213        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
214        if (rtpContentMap == null) {
215            throw new IllegalStateException("initiator RTP Content Map has not been set");
216        }
217        discoverIceServers(iceServers -> {
218            setupWebRTC(iceServers);
219            final org.webrtc.SessionDescription offer = new org.webrtc.SessionDescription(
220                    org.webrtc.SessionDescription.Type.OFFER,
221                    SessionDescription.of(rtpContentMap).toString()
222            );
223            try {
224                this.webRTCWrapper.setRemoteDescription(offer).get();
225                org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
226                final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
227                final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
228                sendSessionAccept(respondingRtpContentMap);
229                this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
230            } catch (Exception e) {
231                Log.d(Config.LOGTAG, "unable to send session accept", e);
232
233            }
234        });
235    }
236
237    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
238        this.responderRtpContentMap = rtpContentMap;
239        this.transitionOrThrow(State.SESSION_ACCEPTED);
240        final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
241        Log.d(Config.LOGTAG, sessionAccept.toString());
242        send(sessionAccept);
243    }
244
245    void deliveryMessage(final Jid from, final Element message) {
246        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
247        switch (message.getName()) {
248            case "propose":
249                receivePropose(from, message);
250                break;
251            case "proceed":
252                receiveProceed(from, message);
253                break;
254            case "retract":
255                receiveRetract(from, message);
256                break;
257            case "reject":
258                receiveReject(from, message);
259                break;
260            case "accept":
261                receiveAccept(from, message);
262                break;
263            default:
264                break;
265        }
266    }
267
268    private void receiveAccept(Jid from, Element message) {
269        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
270        if (originatedFromMyself) {
271            if (transition(State.ACCEPTED)) {
272                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
273                this.jingleConnectionManager.finishConnection(this);
274            } else {
275                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
276            }
277        } else {
278            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
279        }
280    }
281
282    private void receiveReject(Jid from, Element message) {
283        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
284        //reject from another one of my clients
285        if (originatedFromMyself) {
286            if (transition(State.REJECTED)) {
287                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
288                this.jingleConnectionManager.finishConnection(this);
289            } else {
290                Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
291            }
292        } else {
293            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
294        }
295    }
296
297    private void receivePropose(final Jid from, final Element propose) {
298        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
299        //TODO we can use initiator logic here
300        if (originatedFromMyself) {
301            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
302        } else if (transition(State.PROPOSED)) {
303            startRinging();
304        } else {
305            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
306        }
307    }
308
309    private void startRinging() {
310        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
311        xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
312    }
313
314    private void receiveProceed(final Jid from, final Element proceed) {
315        if (from.equals(id.with)) {
316            if (isInitiator()) {
317                if (transition(State.PROCEED)) {
318                    this.sendSessionInitiate(State.SESSION_INITIALIZED_PRE_APPROVED);
319                } else {
320                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
321                }
322            } else {
323                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
324            }
325        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
326            if (transition(State.ACCEPTED)) {
327                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
328                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
329                this.jingleConnectionManager.finishConnection(this);
330            }
331        } else {
332            //TODO a carbon copied proceed from another client of mine has the same logic as `accept`
333            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
334        }
335    }
336
337    private void receiveRetract(final Jid from, final Element retract) {
338        if (from.equals(id.with)) {
339            if (transition(State.RETRACTED)) {
340                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
341                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
342                //TODO create missed call notification/message
343                jingleConnectionManager.finishConnection(this);
344            } else {
345                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
346            }
347        } else {
348            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
349        }
350    }
351
352    private void sendSessionInitiate(final State targetState) {
353        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
354        discoverIceServers(iceServers -> {
355            setupWebRTC(iceServers);
356            try {
357                org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
358                final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
359                Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
360                final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
361                sendSessionInitiate(rtpContentMap, targetState);
362                this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
363            } catch (Exception e) {
364                Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
365            }
366        });
367    }
368
369    private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
370        this.initiatorRtpContentMap = rtpContentMap;
371        this.transitionOrThrow(targetState);
372        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
373        Log.d(Config.LOGTAG, sessionInitiate.toString());
374        send(sessionInitiate);
375    }
376
377    private void sendSessionTerminate(final Reason reason) {
378        final State target = reasonToState(reason);
379        transitionOrThrow(target);
380        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
381        jinglePacket.setReason(reason);
382        send(jinglePacket);
383        Log.d(Config.LOGTAG, jinglePacket.toString());
384        jingleConnectionManager.finishConnection(this);
385    }
386
387    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
388        final RtpContentMap transportInfo;
389        try {
390            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
391            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
392        } catch (Exception e) {
393            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
394            return;
395        }
396        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
397        Log.d(Config.LOGTAG, jinglePacket.toString());
398        send(jinglePacket);
399    }
400
401    private void send(final JinglePacket jinglePacket) {
402        jinglePacket.setTo(id.with);
403        //TODO track errors
404        xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
405    }
406
407    public RtpEndUserState getEndUserState() {
408        switch (this.state) {
409            case PROPOSED:
410            case SESSION_INITIALIZED:
411                if (isInitiator()) {
412                    return RtpEndUserState.RINGING;
413                } else {
414                    return RtpEndUserState.INCOMING_CALL;
415                }
416            case PROCEED:
417                if (isInitiator()) {
418                    return RtpEndUserState.CONNECTING;
419                } else {
420                    return RtpEndUserState.ACCEPTING_CALL;
421                }
422            case SESSION_INITIALIZED_PRE_APPROVED:
423                return RtpEndUserState.CONNECTING;
424            case SESSION_ACCEPTED:
425                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
426                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
427                    return RtpEndUserState.CONNECTED;
428                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
429                    return RtpEndUserState.CONNECTING;
430                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
431                    return RtpEndUserState.ENDING_CALL;
432                } else if (state == PeerConnection.PeerConnectionState.FAILED) {
433                    return RtpEndUserState.CONNECTIVITY_ERROR;
434                } else {
435                    return RtpEndUserState.ENDING_CALL;
436                }
437            case REJECTED:
438            case TERMINATED_DECLINED_OR_BUSY:
439                if (isInitiator()) {
440                    return RtpEndUserState.DECLINED_OR_BUSY;
441                } else {
442                    return RtpEndUserState.ENDED;
443                }
444            case TERMINATED_SUCCESS:
445            case ACCEPTED:
446            case RETRACTED:
447            case TERMINATED_CANCEL_OR_TIMEOUT:
448                return RtpEndUserState.ENDED;
449            case TERMINATED_CONNECTIVITY_ERROR:
450                return RtpEndUserState.CONNECTIVITY_ERROR;
451        }
452        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
453    }
454
455
456    public void acceptCall() {
457        switch (this.state) {
458            case PROPOSED:
459                acceptCallFromProposed();
460                break;
461            case SESSION_INITIALIZED:
462                acceptCallFromSessionInitialized();
463                break;
464            default:
465                throw new IllegalStateException("Can not accept call from " + this.state);
466        }
467    }
468
469    public void rejectCall() {
470        switch (this.state) {
471            case PROPOSED:
472                rejectCallFromProposed();
473                break;
474            default:
475                throw new IllegalStateException("Can not reject call from " + this.state);
476        }
477    }
478
479    public void endCall() {
480        if (isInitiator() && isInState(State.SESSION_INITIALIZED)) {
481            webRTCWrapper.close();
482            sendSessionTerminate(Reason.CANCEL);
483        } else if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
484            webRTCWrapper.close();
485            sendSessionTerminate(Reason.SUCCESS);
486        } else {
487            throw new IllegalStateException("called 'endCall' while in state " + this.state);
488        }
489    }
490
491    private void setupWebRTC(final List<PeerConnection.IceServer> iceServers) {
492        this.webRTCWrapper.setup(this.xmppConnectionService);
493        this.webRTCWrapper.initializePeerConnection(iceServers);
494    }
495
496    private void acceptCallFromProposed() {
497        transitionOrThrow(State.PROCEED);
498        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
499        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
500        this.sendJingleMessage("proceed");
501    }
502
503    private void rejectCallFromProposed() {
504        transitionOrThrow(State.REJECTED);
505        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
506        this.sendJingleMessage("reject");
507        jingleConnectionManager.finishConnection(this);
508    }
509
510    private void sendJingleMessage(final String action) {
511        sendJingleMessage(action, id.with);
512    }
513
514    private void sendJingleMessage(final String action, final Jid to) {
515        final MessagePacket messagePacket = new MessagePacket();
516        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
517        messagePacket.setTo(to);
518        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
519        Log.d(Config.LOGTAG, messagePacket.toString());
520        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
521    }
522
523    private void acceptCallFromSessionInitialized() {
524        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
525        throw new IllegalStateException("accepting from this state has not been implemented yet");
526    }
527
528    private synchronized boolean isInState(State... state) {
529        return Arrays.asList(state).contains(this.state);
530    }
531
532    private synchronized boolean transition(final State target) {
533        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
534        if (validTransitions != null && validTransitions.contains(target)) {
535            this.state = target;
536            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
537            updateEndUserState();
538            return true;
539        } else {
540            return false;
541        }
542    }
543
544    public void transitionOrThrow(final State target) {
545        if (!transition(target)) {
546            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
547        }
548    }
549
550    @Override
551    public void onIceCandidate(final IceCandidate iceCandidate) {
552        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
553        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
554        sendTransportInfo(iceCandidate.sdpMid, candidate);
555    }
556
557    @Override
558    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
559        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
560        updateEndUserState();
561        if (newState == PeerConnection.PeerConnectionState.FAILED) { //TODO guard this in isState(initiated,initated_approved,accepted) otherwise it might fire too late
562            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
563        }
564    }
565
566    private void updateEndUserState() {
567        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
568    }
569
570    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
571        if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
572            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
573            request.setTo(Jid.of(id.account.getJid().getDomain()));
574            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
575            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
576                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
577                if (response.getType() == IqPacket.TYPE.RESULT) {
578                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
579                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
580                    for (final Element child : children) {
581                        if ("service".equals(child.getName())) {
582                            final String type = child.getAttribute("type");
583                            final String host = child.getAttribute("host");
584                            final String port = child.getAttribute("port");
585                            final String transport = child.getAttribute("transport");
586                            final String username = child.getAttribute("username");
587                            final String password = child.getAttribute("password");
588                            if (Arrays.asList("stun", "type").contains(type) && host != null && port != null && "udp".equals(transport)) {
589                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s", type, host, port));
590                                if (username != null && password != null) {
591                                    iceServerBuilder.setUsername(username);
592                                    iceServerBuilder.setPassword(password);
593                                }
594                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
595                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
596                                listBuilder.add(iceServer);
597                            }
598                        }
599                    }
600                }
601                List<PeerConnection.IceServer> iceServers = listBuilder.build();
602                if (iceServers.size() == 0) {
603                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
604                }
605                onIceServersDiscovered.onIceServersDiscovered(iceServers);
606            });
607        } else {
608            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
609            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
610        }
611    }
612
613    private interface OnIceServersDiscovered {
614        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
615    }
616}