1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.PictureInPictureParams;
6import android.content.ActivityNotFoundException;
7import android.content.Context;
8import android.content.Intent;
9import android.content.pm.PackageManager;
10import android.os.Build;
11import android.os.Bundle;
12import android.os.Handler;
13import android.os.PowerManager;
14import android.os.SystemClock;
15import android.util.Log;
16import android.util.Rational;
17import android.view.KeyEvent;
18import android.view.Menu;
19import android.view.MenuItem;
20import android.view.View;
21import android.view.WindowManager;
22import android.widget.Toast;
23
24import androidx.annotation.NonNull;
25import androidx.annotation.RequiresApi;
26import androidx.annotation.StringRes;
27import androidx.databinding.DataBindingUtil;
28
29import com.google.common.base.Optional;
30import com.google.common.base.Preconditions;
31import com.google.common.base.Throwables;
32import com.google.common.collect.ImmutableList;
33import com.google.common.collect.ImmutableSet;
34import com.google.common.util.concurrent.FutureCallback;
35import com.google.common.util.concurrent.Futures;
36
37import org.checkerframework.checker.nullness.compatqual.NullableDecl;
38import org.webrtc.SurfaceViewRenderer;
39import org.webrtc.VideoTrack;
40
41import java.lang.ref.WeakReference;
42import java.util.Arrays;
43import java.util.Collections;
44import java.util.List;
45import java.util.Set;
46
47import eu.siacs.conversations.Config;
48import eu.siacs.conversations.R;
49import eu.siacs.conversations.databinding.ActivityRtpSessionBinding;
50import eu.siacs.conversations.entities.Account;
51import eu.siacs.conversations.entities.Contact;
52import eu.siacs.conversations.entities.Conversation;
53import eu.siacs.conversations.services.AppRTCAudioManager;
54import eu.siacs.conversations.services.XmppConnectionService;
55import eu.siacs.conversations.ui.util.AvatarWorkerTask;
56import eu.siacs.conversations.ui.util.MainThreadExecutor;
57import eu.siacs.conversations.utils.PermissionUtils;
58import eu.siacs.conversations.utils.TimeFrameUtils;
59import eu.siacs.conversations.xml.Namespace;
60import eu.siacs.conversations.xmpp.Jid;
61import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
62import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
63import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
64import eu.siacs.conversations.xmpp.jingle.Media;
65import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
66
67import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
68import static java.util.Arrays.asList;
69
70public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate {
71
72 public static final String EXTRA_WITH = "with";
73 public static final String EXTRA_SESSION_ID = "session_id";
74 public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
75 public static final String EXTRA_LAST_ACTION = "last_action";
76 public static final String ACTION_ACCEPT_CALL = "action_accept_call";
77 public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
78 public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
79
80 private static final int CALL_DURATION_UPDATE_INTERVAL = 333;
81
82 private static final List<RtpEndUserState> END_CARD = Arrays.asList(
83 RtpEndUserState.APPLICATION_ERROR,
84 RtpEndUserState.DECLINED_OR_BUSY,
85 RtpEndUserState.CONNECTIVITY_ERROR,
86 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
87 RtpEndUserState.RETRACTED
88 );
89 private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON = Arrays.asList(
90 RtpEndUserState.APPLICATION_ERROR,
91 RtpEndUserState.CONNECTIVITY_ERROR
92 );
93 private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT = Arrays.asList(
94 RtpEndUserState.CONNECTING,
95 RtpEndUserState.CONNECTED
96 );
97 private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
98 private static final int REQUEST_ACCEPT_CALL = 0x1111;
99 private WeakReference<JingleRtpConnection> rtpConnectionReference;
100
101 private ActivityRtpSessionBinding binding;
102 private PowerManager.WakeLock mProximityWakeLock;
103
104 private final Handler mHandler = new Handler();
105 private final Runnable mTickExecutor = new Runnable() {
106 @Override
107 public void run() {
108 updateCallDuration();
109 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
110 }
111 };
112
113 private static Set<Media> actionToMedia(final String action) {
114 if (ACTION_MAKE_VIDEO_CALL.equals(action)) {
115 return ImmutableSet.of(Media.AUDIO, Media.VIDEO);
116 } else {
117 return ImmutableSet.of(Media.AUDIO);
118 }
119 }
120
121 private static void addSink(final VideoTrack videoTrack, final SurfaceViewRenderer surfaceViewRenderer) {
122 try {
123 videoTrack.addSink(surfaceViewRenderer);
124 } catch (final IllegalStateException e) {
125 Log.e(Config.LOGTAG, "possible race condition on trying to display video track. ignoring", e);
126 }
127 }
128
129 @Override
130 public void onCreate(Bundle savedInstanceState) {
131 super.onCreate(savedInstanceState);
132 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
133 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
134 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
135 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
136 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
137 setSupportActionBar(binding.toolbar);
138 }
139
140 @Override
141 public boolean onCreateOptionsMenu(final Menu menu) {
142 getMenuInflater().inflate(R.menu.activity_rtp_session, menu);
143 final MenuItem help = menu.findItem(R.id.action_help);
144 final MenuItem gotoChat = menu.findItem(R.id.action_goto_chat);
145 help.setVisible(isHelpButtonVisible());
146 gotoChat.setVisible(isSwitchToConversationVisible());
147 return super.onCreateOptionsMenu(menu);
148 }
149
150 @Override
151 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
152 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
153 if (xmppConnectionService != null) {
154 if (xmppConnectionService.getNotificationService().stopSoundAndVibration()) {
155 return true;
156 }
157 }
158 }
159 return super.onKeyDown(keyCode, event);
160 }
161
162 private boolean isHelpButtonVisible() {
163 try {
164 return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState());
165 } catch (IllegalStateException e) {
166 final Intent intent = getIntent();
167 final String state = intent != null ? intent.getStringExtra(EXTRA_LAST_REPORTED_STATE) : null;
168 if (state != null) {
169 return STATES_SHOWING_HELP_BUTTON.contains(RtpEndUserState.valueOf(state));
170 } else {
171 return false;
172 }
173 }
174 }
175
176 private boolean isSwitchToConversationVisible() {
177 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
178 return connection != null && STATES_SHOWING_SWITCH_TO_CHAT.contains(connection.getEndUserState());
179 }
180
181 private void switchToConversation() {
182 final Contact contact = getWith();
183 final Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
184 switchToConversation(conversation);
185 }
186
187 public boolean onOptionsItemSelected(final MenuItem item) {
188 switch (item.getItemId()) {
189 case R.id.action_help:
190 launchHelpInBrowser();
191 break;
192 case R.id.action_goto_chat:
193 switchToConversation();
194 break;
195 }
196 return super.onOptionsItemSelected(item);
197 }
198
199 private void launchHelpInBrowser() {
200 final Intent intent = new Intent(Intent.ACTION_VIEW, Config.HELP);
201 try {
202 startActivity(intent);
203 } catch (final ActivityNotFoundException e) {
204 Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_LONG).show();
205 }
206 }
207
208 private void endCall(View view) {
209 endCall();
210 }
211
212 private void endCall() {
213 if (this.rtpConnectionReference == null) {
214 retractSessionProposal();
215 finish();
216 } else {
217 requireRtpConnection().endCall();
218 }
219 }
220
221 private void retractSessionProposal() {
222 final Intent intent = getIntent();
223 final String action = intent.getAction();
224 final Account account = extractAccount(intent);
225 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
226 final String state = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
227 if (!Intent.ACTION_VIEW.equals(action) || state == null || !END_CARD.contains(RtpEndUserState.valueOf(state))) {
228 resetIntent(account, with, RtpEndUserState.RETRACTED, actionToMedia(intent.getAction()));
229 }
230 xmppConnectionService.getJingleConnectionManager().retractSessionProposal(account, with.asBareJid());
231 }
232
233 private void rejectCall(View view) {
234 requireRtpConnection().rejectCall();
235 finish();
236 }
237
238 private void acceptCall(View view) {
239 requestPermissionsAndAcceptCall();
240 }
241
242 private void requestPermissionsAndAcceptCall() {
243 final List<String> permissions;
244 if (getMedia().contains(Media.VIDEO)) {
245 permissions = ImmutableList.of(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO);
246 } else {
247 permissions = ImmutableList.of(Manifest.permission.RECORD_AUDIO);
248 }
249 if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CALL)) {
250 putScreenInCallMode();
251 checkRecorderAndAcceptCall();
252 }
253 }
254
255 private void checkRecorderAndAcceptCall() {
256 checkMicrophoneAvailability();
257 try {
258 requireRtpConnection().acceptCall();
259 } catch (final IllegalStateException e) {
260 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
261 }
262 }
263
264 private void checkMicrophoneAvailability() {
265 new Thread(() -> {
266 final long start = SystemClock.elapsedRealtime();
267 final boolean isMicrophoneAvailable = AppRTCAudioManager.isMicrophoneAvailable();
268 final long stop = SystemClock.elapsedRealtime();
269 Log.d(Config.LOGTAG, "checking microphone availability took " + (stop - start) + "ms");
270 if (isMicrophoneAvailable) {
271 return;
272 }
273 runOnUiThread(() -> Toast.makeText(this, R.string.microphone_unavailable, Toast.LENGTH_LONG).show());
274 }
275 ).start();
276 }
277
278 private void putScreenInCallMode() {
279 putScreenInCallMode(requireRtpConnection().getMedia());
280 }
281
282 private void putScreenInCallMode(final Set<Media> media) {
283 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
284 if (!media.contains(Media.VIDEO)) {
285 final JingleRtpConnection rtpConnection = rtpConnectionReference != null ? rtpConnectionReference.get() : null;
286 final AppRTCAudioManager audioManager = rtpConnection == null ? null : rtpConnection.getAudioManager();
287 if (audioManager == null || audioManager.getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.EARPIECE) {
288 acquireProximityWakeLock();
289 }
290 }
291 }
292
293 @SuppressLint("WakelockTimeout")
294 private void acquireProximityWakeLock() {
295 final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
296 if (powerManager == null) {
297 Log.e(Config.LOGTAG, "power manager not available");
298 return;
299 }
300 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
301 if (this.mProximityWakeLock == null) {
302 this.mProximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
303 }
304 if (!this.mProximityWakeLock.isHeld()) {
305 Log.d(Config.LOGTAG, "acquiring proximity wake lock");
306 this.mProximityWakeLock.acquire();
307 }
308 }
309 }
310
311 private void releaseProximityWakeLock() {
312 if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
313 Log.d(Config.LOGTAG, "releasing proximity wake lock");
314 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
315 this.mProximityWakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
316 } else {
317 this.mProximityWakeLock.release();
318 }
319 this.mProximityWakeLock = null;
320 }
321 }
322
323 private void putProximityWakeLockInProperState(final AppRTCAudioManager.AudioDevice audioDevice) {
324 if (audioDevice == AppRTCAudioManager.AudioDevice.EARPIECE) {
325 acquireProximityWakeLock();
326 } else {
327 releaseProximityWakeLock();
328 }
329 }
330
331 @Override
332 protected void refreshUiReal() {
333
334 }
335
336 @Override
337 public void onNewIntent(final Intent intent) {
338 Log.d(Config.LOGTAG, this.getClass().getName() + ".onNewIntent()");
339 super.onNewIntent(intent);
340 setIntent(intent);
341 if (xmppConnectionService == null) {
342 Log.d(Config.LOGTAG, "RtpSessionActivity: background service wasn't bound in onNewIntent()");
343 return;
344 }
345 final Account account = extractAccount(intent);
346 final String action = intent.getAction();
347 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
348 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
349 if (sessionId != null) {
350 Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
351 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
352 return;
353 }
354 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
355 Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
356 requestPermissionsAndAcceptCall();
357 resetIntent(intent.getExtras());
358 }
359 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
360 proposeJingleRtpSession(account, with, actionToMedia(action));
361 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
362 } else {
363 throw new IllegalStateException("received onNewIntent without sessionId");
364 }
365 }
366
367 @Override
368 void onBackendConnected() {
369 final Intent intent = getIntent();
370 final String action = intent.getAction();
371 final Account account = extractAccount(intent);
372 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
373 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
374 if (sessionId != null) {
375 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
376 return;
377 }
378 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
379 Log.d(Config.LOGTAG, "intent action was accept");
380 requestPermissionsAndAcceptCall();
381 resetIntent(intent.getExtras());
382 }
383 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
384 proposeJingleRtpSession(account, with, actionToMedia(action));
385 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
386 } else if (Intent.ACTION_VIEW.equals(action)) {
387 final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
388 final RtpEndUserState state = extraLastState == null ? null : RtpEndUserState.valueOf(extraLastState);
389 if (state != null) {
390 Log.d(Config.LOGTAG, "restored last state from intent extra");
391 updateButtonConfiguration(state);
392 updateVerifiedShield(false);
393 updateStateDisplay(state);
394 updateProfilePicture(state);
395 invalidateOptionsMenu();
396 }
397 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
398 if (xmppConnectionService.getJingleConnectionManager().fireJingleRtpConnectionStateUpdates()) {
399 return;
400 }
401 if (END_CARD.contains(state) || xmppConnectionService.getJingleConnectionManager().hasMatchingProposal(account, with)) {
402 return;
403 }
404 Log.d(Config.LOGTAG, "restored state (" + state + ") was not an end card. finishing");
405 finish();
406 }
407 }
408
409 private void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
410 checkMicrophoneAvailability();
411 if (with.isBareJid()) {
412 xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with, media);
413 } else {
414 final String sessionId = xmppConnectionService.getJingleConnectionManager().initializeRtpSession(account, with, media);
415 initializeActivityWithRunningRtpSession(account, with, sessionId);
416 resetIntent(account, with, sessionId);
417 }
418 putScreenInCallMode(media);
419 }
420
421 @Override
422 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
423 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
424 if (PermissionUtils.allGranted(grantResults)) {
425 if (requestCode == REQUEST_ACCEPT_CALL) {
426 checkRecorderAndAcceptCall();
427 }
428 } else {
429 @StringRes int res;
430 final String firstDenied = getFirstDenied(grantResults, permissions);
431 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
432 res = R.string.no_microphone_permission;
433 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
434 res = R.string.no_camera_permission;
435 } else {
436 throw new IllegalStateException("Invalid permission result request");
437 }
438 Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
439 }
440 }
441
442 @Override
443 public void onStart() {
444 super.onStart();
445 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
446 }
447
448 @Override
449 public void onStop() {
450 mHandler.removeCallbacks(mTickExecutor);
451 binding.remoteVideo.release();
452 binding.localVideo.release();
453 final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
454 final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get();
455 if (jingleRtpConnection != null) {
456 releaseVideoTracks(jingleRtpConnection);
457 }
458 releaseProximityWakeLock();
459 super.onStop();
460 }
461
462 private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
463 final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
464 if (remoteVideo.isPresent()) {
465 remoteVideo.get().removeSink(binding.remoteVideo);
466 }
467 final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
468 if (localVideo.isPresent()) {
469 localVideo.get().removeSink(binding.localVideo);
470 }
471 }
472
473 @Override
474 public void onBackPressed() {
475 if (isConnected()) {
476 if (switchToPictureInPicture()) {
477 return;
478 }
479 } else {
480 endCall();
481 }
482 super.onBackPressed();
483 }
484
485 @Override
486 public void onUserLeaveHint() {
487 super.onUserLeaveHint();
488 if (switchToPictureInPicture()) {
489 return;
490 }
491 //TODO apparently this method is not getting called on Android 10 when using the task switcher
492 if (emptyReference(rtpConnectionReference) && xmppConnectionService != null) {
493 retractSessionProposal();
494 }
495 }
496
497 private boolean isConnected() {
498 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
499 return connection != null && connection.getEndUserState() == RtpEndUserState.CONNECTED;
500 }
501
502 private boolean switchToPictureInPicture() {
503 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
504 if (shouldBePictureInPicture()) {
505 startPictureInPicture();
506 return true;
507 }
508 }
509 return false;
510 }
511
512 @RequiresApi(api = Build.VERSION_CODES.O)
513 private void startPictureInPicture() {
514 try {
515 enterPictureInPictureMode(
516 new PictureInPictureParams.Builder()
517 .setAspectRatio(new Rational(10, 16))
518 .build()
519 );
520 } catch (final IllegalStateException e) {
521 //this sometimes happens on Samsung phones (possibly when Knox is enabled)
522 Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
523 }
524 }
525
526 private boolean deviceSupportsPictureInPicture() {
527 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
528 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
529 } else {
530 return false;
531 }
532 }
533
534 private boolean shouldBePictureInPicture() {
535 try {
536 final JingleRtpConnection rtpConnection = requireRtpConnection();
537 return rtpConnection.getMedia().contains(Media.VIDEO) && Arrays.asList(
538 RtpEndUserState.ACCEPTING_CALL,
539 RtpEndUserState.CONNECTING,
540 RtpEndUserState.CONNECTED
541 ).contains(rtpConnection.getEndUserState());
542 } catch (final IllegalStateException e) {
543 return false;
544 }
545 }
546
547 private boolean initializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
548 final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
549 .findJingleRtpConnection(account, with, sessionId);
550 if (reference == null || reference.get() == null) {
551 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession = xmppConnectionService
552 .getJingleConnectionManager().getTerminalSessionState(with, sessionId);
553 if (terminatedRtpSession == null) {
554 throw new IllegalStateException("failed to initialize activity with running rtp session. session not found");
555 }
556 initializeWithTerminatedSessionState(account, with, terminatedRtpSession);
557 return true;
558 }
559 this.rtpConnectionReference = reference;
560 final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
561 final boolean verified = requireRtpConnection().isVerified();
562 if (currentState == RtpEndUserState.ENDED) {
563 reference.get().throwStateTransitionException();
564 finish();
565 return true;
566 }
567 final Set<Media> media = getMedia();
568 if (currentState == RtpEndUserState.INCOMING_CALL) {
569 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
570 }
571 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
572 putScreenInCallMode();
573 }
574 binding.with.setText(getWith().getDisplayName());
575 updateVideoViews(currentState);
576 updateStateDisplay(currentState, media);
577 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
578 updateButtonConfiguration(currentState, media);
579 updateProfilePicture(currentState);
580 invalidateOptionsMenu();
581 return false;
582 }
583
584 private void initializeWithTerminatedSessionState(final Account account, final Jid with, final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
585 Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
586 if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
587 finish();
588 return;
589 }
590 RtpEndUserState state = terminatedRtpSession.state;
591 resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
592 updateButtonConfiguration(state);
593 updateStateDisplay(state);
594 updateProfilePicture(state);
595 updateCallDuration();
596 updateVerifiedShield(false);
597 invalidateOptionsMenu();
598 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
599 }
600
601 private void reInitializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
602 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
603 resetIntent(account, with, sessionId);
604 }
605
606 private void resetIntent(final Account account, final Jid with, final String sessionId) {
607 final Intent intent = new Intent(Intent.ACTION_VIEW);
608 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
609 intent.putExtra(EXTRA_WITH, with.toEscapedString());
610 intent.putExtra(EXTRA_SESSION_ID, sessionId);
611 setIntent(intent);
612 }
613
614 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
615 surfaceViewRenderer.setVisibility(View.VISIBLE);
616 try {
617 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
618 } catch (IllegalStateException e) {
619 Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
620 }
621 surfaceViewRenderer.setEnableHardwareScaler(true);
622 }
623
624 private void updateStateDisplay(final RtpEndUserState state) {
625 updateStateDisplay(state, Collections.emptySet());
626 }
627
628 private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
629 switch (state) {
630 case INCOMING_CALL:
631 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
632 if (media.contains(Media.VIDEO)) {
633 setTitle(R.string.rtp_state_incoming_video_call);
634 } else {
635 setTitle(R.string.rtp_state_incoming_call);
636 }
637 break;
638 case CONNECTING:
639 setTitle(R.string.rtp_state_connecting);
640 break;
641 case CONNECTED:
642 setTitle(R.string.rtp_state_connected);
643 break;
644 case ACCEPTING_CALL:
645 setTitle(R.string.rtp_state_accepting_call);
646 break;
647 case ENDING_CALL:
648 setTitle(R.string.rtp_state_ending_call);
649 break;
650 case FINDING_DEVICE:
651 setTitle(R.string.rtp_state_finding_device);
652 break;
653 case RINGING:
654 setTitle(R.string.rtp_state_ringing);
655 break;
656 case DECLINED_OR_BUSY:
657 setTitle(R.string.rtp_state_declined_or_busy);
658 break;
659 case CONNECTIVITY_ERROR:
660 setTitle(R.string.rtp_state_connectivity_error);
661 break;
662 case CONNECTIVITY_LOST_ERROR:
663 setTitle(R.string.rtp_state_connectivity_lost_error);
664 break;
665 case RETRACTED:
666 setTitle(R.string.rtp_state_retracted);
667 break;
668 case APPLICATION_ERROR:
669 setTitle(R.string.rtp_state_application_failure);
670 break;
671 case ENDED:
672 throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
673 default:
674 throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
675 }
676 }
677
678 private void updateVerifiedShield(final boolean verified) {
679 if (isPictureInPicture()) {
680 this.binding.verified.setVisibility(View.GONE);
681 return;
682 }
683 this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
684 }
685
686 private void updateProfilePicture(final RtpEndUserState state) {
687 updateProfilePicture(state, null);
688 }
689
690 private void updateProfilePicture(final RtpEndUserState state, final Contact contact) {
691 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
692 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
693 if (show) {
694 binding.contactPhoto.setVisibility(View.VISIBLE);
695 if (contact == null) {
696 AvatarWorkerTask.loadAvatar(getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
697 } else {
698 AvatarWorkerTask.loadAvatar(contact, binding.contactPhoto, R.dimen.publish_avatar_size);
699 }
700 } else {
701 binding.contactPhoto.setVisibility(View.GONE);
702 }
703 } else {
704 binding.contactPhoto.setVisibility(View.GONE);
705 }
706 }
707
708 private Set<Media> getMedia() {
709 return requireRtpConnection().getMedia();
710 }
711
712 private void updateButtonConfiguration(final RtpEndUserState state) {
713 updateButtonConfiguration(state, Collections.emptySet());
714 }
715
716 @SuppressLint("RestrictedApi")
717 private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
718 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
719 this.binding.rejectCall.setVisibility(View.INVISIBLE);
720 this.binding.endCall.setVisibility(View.INVISIBLE);
721 this.binding.acceptCall.setVisibility(View.INVISIBLE);
722 } else if (state == RtpEndUserState.INCOMING_CALL) {
723 this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
724 this.binding.rejectCall.setOnClickListener(this::rejectCall);
725 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
726 this.binding.rejectCall.setVisibility(View.VISIBLE);
727 this.binding.endCall.setVisibility(View.INVISIBLE);
728 this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
729 this.binding.acceptCall.setOnClickListener(this::acceptCall);
730 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
731 this.binding.acceptCall.setVisibility(View.VISIBLE);
732 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
733 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
734 this.binding.rejectCall.setOnClickListener(this::exit);
735 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
736 this.binding.rejectCall.setVisibility(View.VISIBLE);
737 this.binding.endCall.setVisibility(View.INVISIBLE);
738 this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
739 this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
740 this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
741 this.binding.acceptCall.setVisibility(View.VISIBLE);
742 } else if (asList(
743 RtpEndUserState.CONNECTIVITY_ERROR,
744 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
745 RtpEndUserState.APPLICATION_ERROR,
746 RtpEndUserState.RETRACTED
747 ).contains(state)) {
748 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
749 this.binding.rejectCall.setOnClickListener(this::exit);
750 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
751 this.binding.rejectCall.setVisibility(View.VISIBLE);
752 this.binding.endCall.setVisibility(View.INVISIBLE);
753 this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
754 this.binding.acceptCall.setOnClickListener(this::retry);
755 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
756 this.binding.acceptCall.setVisibility(View.VISIBLE);
757 } else {
758 this.binding.rejectCall.setVisibility(View.INVISIBLE);
759 this.binding.endCall.setContentDescription(getString(R.string.hang_up));
760 this.binding.endCall.setOnClickListener(this::endCall);
761 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
762 this.binding.endCall.setVisibility(View.VISIBLE);
763 this.binding.acceptCall.setVisibility(View.INVISIBLE);
764 }
765 updateInCallButtonConfiguration(state, media);
766 }
767
768 private boolean isPictureInPicture() {
769 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
770 return isInPictureInPictureMode();
771 } else {
772 return false;
773 }
774 }
775
776 private void updateInCallButtonConfiguration() {
777 updateInCallButtonConfiguration(requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
778 }
779
780 @SuppressLint("RestrictedApi")
781 private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
782 if (state == RtpEndUserState.CONNECTED && !isPictureInPicture()) {
783 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
784 if (media.contains(Media.VIDEO)) {
785 final JingleRtpConnection rtpConnection = requireRtpConnection();
786 updateInCallButtonConfigurationVideo(rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
787 } else {
788 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
789 updateInCallButtonConfigurationSpeaker(
790 audioManager.getSelectedAudioDevice(),
791 audioManager.getAudioDevices().size()
792 );
793 this.binding.inCallActionFarRight.setVisibility(View.GONE);
794 }
795 if (media.contains(Media.AUDIO)) {
796 updateInCallButtonConfigurationMicrophone(requireRtpConnection().isMicrophoneEnabled());
797 } else {
798 this.binding.inCallActionLeft.setVisibility(View.GONE);
799 }
800 } else {
801 this.binding.inCallActionLeft.setVisibility(View.GONE);
802 this.binding.inCallActionRight.setVisibility(View.GONE);
803 this.binding.inCallActionFarRight.setVisibility(View.GONE);
804 }
805 }
806
807 @SuppressLint("RestrictedApi")
808 private void updateInCallButtonConfigurationSpeaker(final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
809 switch (selectedAudioDevice) {
810 case EARPIECE:
811 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_off_black_24dp);
812 if (numberOfChoices >= 2) {
813 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
814 } else {
815 this.binding.inCallActionRight.setOnClickListener(null);
816 this.binding.inCallActionRight.setClickable(false);
817 }
818 break;
819 case WIRED_HEADSET:
820 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
821 this.binding.inCallActionRight.setOnClickListener(null);
822 this.binding.inCallActionRight.setClickable(false);
823 break;
824 case SPEAKER_PHONE:
825 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
826 if (numberOfChoices >= 2) {
827 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
828 } else {
829 this.binding.inCallActionRight.setOnClickListener(null);
830 this.binding.inCallActionRight.setClickable(false);
831 }
832 break;
833 case BLUETOOTH:
834 this.binding.inCallActionRight.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
835 this.binding.inCallActionRight.setOnClickListener(null);
836 this.binding.inCallActionRight.setClickable(false);
837 break;
838 }
839 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
840 }
841
842 @SuppressLint("RestrictedApi")
843 private void updateInCallButtonConfigurationVideo(final boolean videoEnabled, final boolean isCameraSwitchable) {
844 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
845 if (isCameraSwitchable) {
846 this.binding.inCallActionFarRight.setImageResource(R.drawable.ic_flip_camera_android_black_24dp);
847 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
848 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
849 } else {
850 this.binding.inCallActionFarRight.setVisibility(View.GONE);
851 }
852 if (videoEnabled) {
853 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
854 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
855 } else {
856 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
857 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
858 }
859 }
860
861 private void switchCamera(final View view) {
862 Futures.addCallback(requireRtpConnection().switchCamera(), new FutureCallback<Boolean>() {
863 @Override
864 public void onSuccess(@NullableDecl Boolean isFrontCamera) {
865 binding.localVideo.setMirror(isFrontCamera);
866 }
867
868 @Override
869 public void onFailure(@NonNull final Throwable throwable) {
870 Log.d(Config.LOGTAG, "could not switch camera", Throwables.getRootCause(throwable));
871 Toast.makeText(RtpSessionActivity.this, R.string.could_not_switch_camera, Toast.LENGTH_LONG).show();
872 }
873 }, MainThreadExecutor.getInstance());
874 }
875
876 private void enableVideo(View view) {
877 requireRtpConnection().setVideoEnabled(true);
878 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
879 }
880
881 private void disableVideo(View view) {
882 requireRtpConnection().setVideoEnabled(false);
883 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
884
885 }
886
887 @SuppressLint("RestrictedApi")
888 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
889 if (microphoneEnabled) {
890 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
891 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
892 } else {
893 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
894 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
895 }
896 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
897 }
898
899 private void updateCallDuration() {
900 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
901 if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
902 this.binding.duration.setVisibility(View.GONE);
903 return;
904 }
905 final long rtpConnectionStarted = connection.getRtpConnectionStarted();
906 final long rtpConnectionEnded = connection.getRtpConnectionEnded();
907 if (rtpConnectionStarted != 0) {
908 final long ended = rtpConnectionEnded == 0 ? SystemClock.elapsedRealtime() : rtpConnectionEnded;
909 this.binding.duration.setText(TimeFrameUtils.formatTimePassed(rtpConnectionStarted, ended, false));
910 this.binding.duration.setVisibility(View.VISIBLE);
911 } else {
912 this.binding.duration.setVisibility(View.GONE);
913 }
914 }
915
916 private void updateVideoViews(final RtpEndUserState state) {
917 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
918 binding.localVideo.setVisibility(View.GONE);
919 binding.localVideo.release();
920 binding.remoteVideo.setVisibility(View.GONE);
921 binding.remoteVideo.release();
922 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
923 if (isPictureInPicture()) {
924 binding.appBarLayout.setVisibility(View.GONE);
925 binding.pipPlaceholder.setVisibility(View.VISIBLE);
926 if (state == RtpEndUserState.APPLICATION_ERROR || state == RtpEndUserState.CONNECTIVITY_ERROR) {
927 binding.pipWarning.setVisibility(View.VISIBLE);
928 binding.pipWaiting.setVisibility(View.GONE);
929 } else {
930 binding.pipWarning.setVisibility(View.GONE);
931 binding.pipWaiting.setVisibility(View.GONE);
932 }
933 } else {
934 binding.appBarLayout.setVisibility(View.VISIBLE);
935 binding.pipPlaceholder.setVisibility(View.GONE);
936 }
937 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
938 return;
939 }
940 if (isPictureInPicture() && (state == RtpEndUserState.CONNECTING || state == RtpEndUserState.ACCEPTING_CALL)) {
941 binding.localVideo.setVisibility(View.GONE);
942 binding.remoteVideo.setVisibility(View.GONE);
943 binding.appBarLayout.setVisibility(View.GONE);
944 binding.pipPlaceholder.setVisibility(View.VISIBLE);
945 binding.pipWarning.setVisibility(View.GONE);
946 binding.pipWaiting.setVisibility(View.VISIBLE);
947 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
948 return;
949 }
950 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
951 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
952 ensureSurfaceViewRendererIsSetup(binding.localVideo);
953 //paint local view over remote view
954 binding.localVideo.setZOrderMediaOverlay(true);
955 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
956 addSink(localVideoTrack.get(), binding.localVideo);
957 } else {
958 binding.localVideo.setVisibility(View.GONE);
959 }
960 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
961 if (remoteVideoTrack.isPresent()) {
962 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
963 addSink(remoteVideoTrack.get(), binding.remoteVideo);
964 if (state == RtpEndUserState.CONNECTED) {
965 binding.appBarLayout.setVisibility(View.GONE);
966 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
967 } else {
968 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
969 binding.remoteVideo.setVisibility(View.GONE);
970 }
971 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
972 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
973 } else {
974 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
975 }
976 } else {
977 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
978 binding.remoteVideo.setVisibility(View.GONE);
979 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
980 }
981 }
982
983 private Optional<VideoTrack> getLocalVideoTrack() {
984 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
985 if (connection == null) {
986 return Optional.absent();
987 }
988 return connection.getLocalVideoTrack();
989 }
990
991 private Optional<VideoTrack> getRemoteVideoTrack() {
992 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
993 if (connection == null) {
994 return Optional.absent();
995 }
996 return connection.getRemoteVideoTrack();
997 }
998
999 private void disableMicrophone(View view) {
1000 final JingleRtpConnection rtpConnection = requireRtpConnection();
1001 if (rtpConnection.setMicrophoneEnabled(false)) {
1002 updateInCallButtonConfiguration();
1003 }
1004 }
1005
1006 private void enableMicrophone(View view) {
1007 final JingleRtpConnection rtpConnection = requireRtpConnection();
1008 if (rtpConnection.setMicrophoneEnabled(true)) {
1009 updateInCallButtonConfiguration();
1010 }
1011 }
1012
1013 private void switchToEarpiece(View view) {
1014 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1015 acquireProximityWakeLock();
1016 }
1017
1018 private void switchToSpeaker(View view) {
1019 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1020 releaseProximityWakeLock();
1021 }
1022
1023 private void retry(View view) {
1024 final Intent intent = getIntent();
1025 final Account account = extractAccount(intent);
1026 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1027 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1028 final String action = intent.getAction();
1029 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1030 this.rtpConnectionReference = null;
1031 Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1032 proposeJingleRtpSession(account, with, media);
1033 }
1034
1035 private void exit(final View view) {
1036 finish();
1037 }
1038
1039 private void recordVoiceMail(final View view) {
1040 final Intent intent = getIntent();
1041 final Account account = extractAccount(intent);
1042 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1043 final Conversation conversation = xmppConnectionService.findOrCreateConversation(account, with, false, true);
1044 final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1045 launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1046 launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1047 launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1048 launchIntent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, ConversationsActivity.POST_ACTION_RECORD_VOICE);
1049 startActivity(launchIntent);
1050 finish();
1051 }
1052
1053 private Contact getWith() {
1054 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1055 final Account account = id.account;
1056 return account.getRoster().getContact(id.with);
1057 }
1058
1059 private JingleRtpConnection requireRtpConnection() {
1060 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1061 if (connection == null) {
1062 throw new IllegalStateException("No RTP connection found");
1063 }
1064 return connection;
1065 }
1066
1067 @Override
1068 public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
1069 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1070 if (END_CARD.contains(state)) {
1071 Log.d(Config.LOGTAG, "end card reached");
1072 releaseProximityWakeLock();
1073 runOnUiThread(() -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1074 }
1075 if (with.isBareJid()) {
1076 updateRtpSessionProposalState(account, with, state);
1077 return;
1078 }
1079 if (emptyReference(this.rtpConnectionReference)) {
1080 if (END_CARD.contains(state)) {
1081 Log.d(Config.LOGTAG, "not reinitializing session");
1082 return;
1083 }
1084 //this happens when going from proposed session to actual session
1085 reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1086 return;
1087 }
1088 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1089 final boolean verified = requireRtpConnection().isVerified();
1090 final Set<Media> media = getMedia();
1091 final Contact contact = getWith();
1092 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1093 if (state == RtpEndUserState.ENDED) {
1094 finish();
1095 return;
1096 }
1097 runOnUiThread(() -> {
1098 updateStateDisplay(state, media);
1099 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1100 updateButtonConfiguration(state, media);
1101 updateVideoViews(state);
1102 updateProfilePicture(state, contact);
1103 invalidateOptionsMenu();
1104 });
1105 if (END_CARD.contains(state)) {
1106 final JingleRtpConnection rtpConnection = requireRtpConnection();
1107 resetIntent(account, with, state, rtpConnection.getMedia());
1108 releaseVideoTracks(rtpConnection);
1109 this.rtpConnectionReference = null;
1110 }
1111 } else {
1112 Log.d(Config.LOGTAG, "received update for other rtp session");
1113 }
1114 }
1115
1116 @Override
1117 public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1118 Log.d(Config.LOGTAG, "onAudioDeviceChanged in activity: selected:" + selectedAudioDevice + ", available:" + availableAudioDevices);
1119 try {
1120 if (getMedia().contains(Media.VIDEO)) {
1121 Log.d(Config.LOGTAG, "nothing to do; in video mode");
1122 return;
1123 }
1124 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1125 if (endUserState == RtpEndUserState.CONNECTED) {
1126 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1127 updateInCallButtonConfigurationSpeaker(
1128 audioManager.getSelectedAudioDevice(),
1129 audioManager.getAudioDevices().size()
1130 );
1131 } else if (END_CARD.contains(endUserState)) {
1132 Log.d(Config.LOGTAG, "onAudioDeviceChanged() nothing to do because end card has been reached");
1133 } else {
1134 putProximityWakeLockInProperState(selectedAudioDevice);
1135 }
1136 } catch (IllegalStateException e) {
1137 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1138 }
1139 }
1140
1141 private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
1142 final Intent currentIntent = getIntent();
1143 final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1144 if (withExtra == null) {
1145 return;
1146 }
1147 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1148 runOnUiThread(() -> {
1149 updateVerifiedShield(false);
1150 updateStateDisplay(state);
1151 updateButtonConfiguration(state);
1152 updateProfilePicture(state);
1153 invalidateOptionsMenu();
1154 });
1155 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1156 }
1157 }
1158
1159 private void resetIntent(final Bundle extras) {
1160 final Intent intent = new Intent(Intent.ACTION_VIEW);
1161 intent.putExtras(extras);
1162 setIntent(intent);
1163 }
1164
1165 private void resetIntent(final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1166 final Intent intent = new Intent(Intent.ACTION_VIEW);
1167 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1168 if (account.getRoster().getContact(with).getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1169 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1170 } else {
1171 intent.putExtra(EXTRA_WITH, with.toEscapedString());
1172 }
1173 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1174 intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1175 setIntent(intent);
1176 }
1177
1178 private static boolean emptyReference(final WeakReference<?> weakReference) {
1179 return weakReference == null || weakReference.get() == null;
1180 }
1181}