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