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 final SessionDescription offer;
218 try {
219 offer = SessionDescription.of(rtpContentMap);
220 } catch (final IllegalArgumentException e) {
221 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to process offer", e);
222 //TODO terminate session with application error
223 return;
224 }
225 sendSessionAccept(offer);
226 }
227
228 private void sendSessionAccept(SessionDescription offer) {
229 discoverIceServers(iceServers -> {
230 setupWebRTC(iceServers);
231 final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
232 org.webrtc.SessionDescription.Type.OFFER,
233 offer.toString()
234 );
235 try {
236 this.webRTCWrapper.setRemoteDescription(sdp).get();
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 sendSessionAccept(final RtpContentMap rtpContentMap) {
250 this.responderRtpContentMap = rtpContentMap;
251 this.transitionOrThrow(State.SESSION_ACCEPTED);
252 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
253 Log.d(Config.LOGTAG, sessionAccept.toString());
254 send(sessionAccept);
255 }
256
257 void deliveryMessage(final Jid from, final Element message) {
258 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
259 switch (message.getName()) {
260 case "propose":
261 receivePropose(from, message);
262 break;
263 case "proceed":
264 receiveProceed(from, message);
265 break;
266 case "retract":
267 receiveRetract(from, message);
268 break;
269 case "reject":
270 receiveReject(from, message);
271 break;
272 case "accept":
273 receiveAccept(from, message);
274 break;
275 default:
276 break;
277 }
278 }
279
280 private void receiveAccept(Jid from, Element message) {
281 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
282 if (originatedFromMyself) {
283 if (transition(State.ACCEPTED)) {
284 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
285 this.jingleConnectionManager.finishConnection(this);
286 } else {
287 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
288 }
289 } else {
290 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
291 }
292 }
293
294 private void receiveReject(Jid from, Element message) {
295 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
296 //reject from another one of my clients
297 if (originatedFromMyself) {
298 if (transition(State.REJECTED)) {
299 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
300 this.jingleConnectionManager.finishConnection(this);
301 } else {
302 Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
303 }
304 } else {
305 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
306 }
307 }
308
309 private void receivePropose(final Jid from, final Element propose) {
310 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
311 //TODO we can use initiator logic here
312 if (originatedFromMyself) {
313 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
314 } else if (transition(State.PROPOSED)) {
315 startRinging();
316 } else {
317 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
318 }
319 }
320
321 private void startRinging() {
322 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
323 xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
324 }
325
326 private void receiveProceed(final Jid from, final Element proceed) {
327 if (from.equals(id.with)) {
328 if (isInitiator()) {
329 if (transition(State.PROCEED)) {
330 this.sendSessionInitiate(State.SESSION_INITIALIZED_PRE_APPROVED);
331 } else {
332 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
333 }
334 } else {
335 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
336 }
337 } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
338 if (transition(State.ACCEPTED)) {
339 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
340 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
341 this.jingleConnectionManager.finishConnection(this);
342 }
343 } else {
344 //TODO a carbon copied proceed from another client of mine has the same logic as `accept`
345 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
346 }
347 }
348
349 private void receiveRetract(final Jid from, final Element retract) {
350 if (from.equals(id.with)) {
351 if (transition(State.RETRACTED)) {
352 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
353 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
354 //TODO create missed call notification/message
355 jingleConnectionManager.finishConnection(this);
356 } else {
357 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
358 }
359 } else {
360 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
361 }
362 }
363
364 private void sendSessionInitiate(final State targetState) {
365 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
366 discoverIceServers(iceServers -> {
367 setupWebRTC(iceServers);
368 try {
369 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
370 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
371 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
372 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
373 sendSessionInitiate(rtpContentMap, targetState);
374 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
375 } catch (Exception e) {
376 Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
377 }
378 });
379 }
380
381 private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
382 this.initiatorRtpContentMap = rtpContentMap;
383 this.transitionOrThrow(targetState);
384 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
385 Log.d(Config.LOGTAG, sessionInitiate.toString());
386 send(sessionInitiate);
387 }
388
389 private void sendSessionTerminate(final Reason reason) {
390 final State target = reasonToState(reason);
391 transitionOrThrow(target);
392 final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
393 jinglePacket.setReason(reason);
394 send(jinglePacket);
395 Log.d(Config.LOGTAG, jinglePacket.toString());
396 jingleConnectionManager.finishConnection(this);
397 }
398
399 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
400 final RtpContentMap transportInfo;
401 try {
402 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
403 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
404 } catch (Exception e) {
405 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
406 return;
407 }
408 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
409 Log.d(Config.LOGTAG, jinglePacket.toString());
410 send(jinglePacket);
411 }
412
413 private void send(final JinglePacket jinglePacket) {
414 jinglePacket.setTo(id.with);
415 //TODO track errors
416 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
417 }
418
419 public RtpEndUserState getEndUserState() {
420 switch (this.state) {
421 case PROPOSED:
422 case SESSION_INITIALIZED:
423 if (isInitiator()) {
424 return RtpEndUserState.RINGING;
425 } else {
426 return RtpEndUserState.INCOMING_CALL;
427 }
428 case PROCEED:
429 if (isInitiator()) {
430 return RtpEndUserState.CONNECTING;
431 } else {
432 return RtpEndUserState.ACCEPTING_CALL;
433 }
434 case SESSION_INITIALIZED_PRE_APPROVED:
435 return RtpEndUserState.CONNECTING;
436 case SESSION_ACCEPTED:
437 final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
438 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
439 return RtpEndUserState.CONNECTED;
440 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
441 return RtpEndUserState.CONNECTING;
442 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
443 return RtpEndUserState.ENDING_CALL;
444 } else if (state == PeerConnection.PeerConnectionState.FAILED) {
445 return RtpEndUserState.CONNECTIVITY_ERROR;
446 } else {
447 return RtpEndUserState.ENDING_CALL;
448 }
449 case REJECTED:
450 case TERMINATED_DECLINED_OR_BUSY:
451 if (isInitiator()) {
452 return RtpEndUserState.DECLINED_OR_BUSY;
453 } else {
454 return RtpEndUserState.ENDED;
455 }
456 case TERMINATED_SUCCESS:
457 case ACCEPTED:
458 case RETRACTED:
459 case TERMINATED_CANCEL_OR_TIMEOUT:
460 return RtpEndUserState.ENDED;
461 case TERMINATED_CONNECTIVITY_ERROR:
462 return RtpEndUserState.CONNECTIVITY_ERROR;
463 }
464 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
465 }
466
467
468 public void acceptCall() {
469 switch (this.state) {
470 case PROPOSED:
471 acceptCallFromProposed();
472 break;
473 case SESSION_INITIALIZED:
474 acceptCallFromSessionInitialized();
475 break;
476 default:
477 throw new IllegalStateException("Can not accept call from " + this.state);
478 }
479 }
480
481 public void rejectCall() {
482 switch (this.state) {
483 case PROPOSED:
484 rejectCallFromProposed();
485 break;
486 default:
487 throw new IllegalStateException("Can not reject call from " + this.state);
488 }
489 }
490
491 public void endCall() {
492 if (isInitiator() && isInState(State.SESSION_INITIALIZED)) {
493 webRTCWrapper.close();
494 sendSessionTerminate(Reason.CANCEL);
495 } else if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
496 webRTCWrapper.close();
497 sendSessionTerminate(Reason.SUCCESS);
498 } else {
499 throw new IllegalStateException("called 'endCall' while in state " + this.state);
500 }
501 }
502
503 private void setupWebRTC(final List<PeerConnection.IceServer> iceServers) {
504 this.webRTCWrapper.setup(this.xmppConnectionService);
505 this.webRTCWrapper.initializePeerConnection(iceServers);
506 }
507
508 private void acceptCallFromProposed() {
509 transitionOrThrow(State.PROCEED);
510 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
511 this.sendJingleMessage("accept", id.account.getJid().asBareJid());
512 this.sendJingleMessage("proceed");
513 }
514
515 private void rejectCallFromProposed() {
516 transitionOrThrow(State.REJECTED);
517 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
518 this.sendJingleMessage("reject");
519 jingleConnectionManager.finishConnection(this);
520 }
521
522 private void sendJingleMessage(final String action) {
523 sendJingleMessage(action, id.with);
524 }
525
526 private void sendJingleMessage(final String action, final Jid to) {
527 final MessagePacket messagePacket = new MessagePacket();
528 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
529 messagePacket.setTo(to);
530 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
531 Log.d(Config.LOGTAG, messagePacket.toString());
532 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
533 }
534
535 private void acceptCallFromSessionInitialized() {
536 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
537 throw new IllegalStateException("accepting from this state has not been implemented yet");
538 }
539
540 private synchronized boolean isInState(State... state) {
541 return Arrays.asList(state).contains(this.state);
542 }
543
544 private synchronized boolean transition(final State target) {
545 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
546 if (validTransitions != null && validTransitions.contains(target)) {
547 this.state = target;
548 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
549 updateEndUserState();
550 return true;
551 } else {
552 return false;
553 }
554 }
555
556 public void transitionOrThrow(final State target) {
557 if (!transition(target)) {
558 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
559 }
560 }
561
562 @Override
563 public void onIceCandidate(final IceCandidate iceCandidate) {
564 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
565 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
566 sendTransportInfo(iceCandidate.sdpMid, candidate);
567 }
568
569 @Override
570 public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
571 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
572 updateEndUserState();
573 if (newState == PeerConnection.PeerConnectionState.FAILED) { //TODO guard this in isState(initiated,initated_approved,accepted) otherwise it might fire too late
574 sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
575 }
576 }
577
578 private void updateEndUserState() {
579 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
580 }
581
582 private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
583 if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
584 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
585 request.setTo(Jid.of(id.account.getJid().getDomain()));
586 request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
587 xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
588 ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
589 if (response.getType() == IqPacket.TYPE.RESULT) {
590 final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
591 final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
592 for (final Element child : children) {
593 if ("service".equals(child.getName())) {
594 final String type = child.getAttribute("type");
595 final String host = child.getAttribute("host");
596 final String port = child.getAttribute("port");
597 final String transport = child.getAttribute("transport");
598 final String username = child.getAttribute("username");
599 final String password = child.getAttribute("password");
600 if (Arrays.asList("stun", "type").contains(type) && host != null && port != null && "udp".equals(transport)) {
601 PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s", type, host, port));
602 if (username != null && password != null) {
603 iceServerBuilder.setUsername(username);
604 iceServerBuilder.setPassword(password);
605 }
606 final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
607 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
608 listBuilder.add(iceServer);
609 }
610 }
611 }
612 }
613 List<PeerConnection.IceServer> iceServers = listBuilder.build();
614 if (iceServers.size() == 0) {
615 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
616 }
617 onIceServersDiscovered.onIceServersDiscovered(iceServers);
618 });
619 } else {
620 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
621 onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
622 }
623 }
624
625 private interface OnIceServersDiscovered {
626 void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
627 }
628}