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