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