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