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