RtpSessionActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import android.Manifest;
  4import android.annotation.SuppressLint;
  5import android.content.Context;
  6import android.content.Intent;
  7import android.databinding.DataBindingUtil;
  8import android.os.Build;
  9import android.os.Bundle;
 10import android.os.PowerManager;
 11import android.support.annotation.NonNull;
 12import android.support.annotation.StringRes;
 13import android.support.v4.content.ContextCompat;
 14import android.util.Log;
 15import android.view.View;
 16import android.view.WindowManager;
 17import android.widget.Toast;
 18
 19import com.google.common.collect.ImmutableList;
 20
 21import java.lang.ref.WeakReference;
 22import java.util.Arrays;
 23import java.util.Set;
 24
 25import eu.siacs.conversations.Config;
 26import eu.siacs.conversations.R;
 27import eu.siacs.conversations.databinding.ActivityRtpSessionBinding;
 28import eu.siacs.conversations.entities.Account;
 29import eu.siacs.conversations.entities.Contact;
 30import eu.siacs.conversations.services.AppRTCAudioManager;
 31import eu.siacs.conversations.services.XmppConnectionService;
 32import eu.siacs.conversations.utils.PermissionUtils;
 33import eu.siacs.conversations.utils.ThemeHelper;
 34import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 35import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
 36import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 37import rocks.xmpp.addr.Jid;
 38
 39import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
 40import static java.util.Arrays.asList;
 41
 42//TODO if last state was BUSY (or RETRY); we want to reset action to view or something so we don’t automatically call again on recreate
 43
 44public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate {
 45
 46    private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
 47
 48    private static final int REQUEST_ACCEPT_CALL = 0x1111;
 49
 50    public static final String EXTRA_WITH = "with";
 51    public static final String EXTRA_SESSION_ID = "session_id";
 52    public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
 53
 54    public static final String ACTION_ACCEPT_CALL = "action_accept_call";
 55    public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
 56    public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
 57
 58    private WeakReference<JingleRtpConnection> rtpConnectionReference;
 59
 60    private ActivityRtpSessionBinding binding;
 61    private PowerManager.WakeLock mProximityWakeLock;
 62
 63    private static AppRTCAudioManager audioManager;
 64
 65    @Override
 66    public void onCreate(Bundle savedInstanceState) {
 67        super.onCreate(savedInstanceState);
 68        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
 69                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
 70                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
 71                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
 72        Log.d(Config.LOGTAG, "RtpSessionActivity.onCreate()");
 73        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
 74    }
 75
 76    @Override
 77    public void onStart() {
 78        super.onStart();
 79        Log.d(Config.LOGTAG, "RtpSessionActivity.onStart()");
 80    }
 81
 82    private void endCall(View view) {
 83        endCall();
 84    }
 85
 86    private void endCall() {
 87        if (this.rtpConnectionReference == null) {
 88            final Intent intent = getIntent();
 89            final Account account = extractAccount(intent);
 90            final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
 91            xmppConnectionService.getJingleConnectionManager().retractSessionProposal(account, with.asBareJid());
 92            finish();
 93        } else {
 94            requireRtpConnection().endCall();
 95        }
 96    }
 97
 98    private void rejectCall(View view) {
 99        requireRtpConnection().rejectCall();
100        finish();
101    }
102
103    private void acceptCall(View view) {
104        requestPermissionsAndAcceptCall();
105    }
106
107    private void requestPermissionsAndAcceptCall() {
108        if (PermissionUtils.hasPermission(this, ImmutableList.of(Manifest.permission.RECORD_AUDIO), REQUEST_ACCEPT_CALL)) {
109            putScreenInCallMode();
110            requireRtpConnection().acceptCall();
111        }
112    }
113
114    @SuppressLint("WakelockTimeout")
115    private void putScreenInCallMode() {
116        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
117        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
118        if (powerManager == null) {
119            Log.e(Config.LOGTAG, "power manager not available");
120            return;
121        }
122        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
123            if (this.mProximityWakeLock == null) {
124                this.mProximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
125            }
126            if (!this.mProximityWakeLock.isHeld()) {
127                Log.d(Config.LOGTAG, "acquiring wake lock");
128                this.mProximityWakeLock.acquire();
129            }
130        }
131    }
132
133    private void releaseWakeLock() {
134        if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
135            Log.d(Config.LOGTAG, "releasing wake lock");
136            this.mProximityWakeLock.release();
137            this.mProximityWakeLock = null;
138        }
139    }
140
141    @Override
142    protected void refreshUiReal() {
143
144    }
145
146    @Override
147    public void onNewIntent(final Intent intent) {
148        super.onNewIntent(intent);
149        setIntent(intent);
150        if (xmppConnectionService == null) {
151            Log.d(Config.LOGTAG, "RtpSessionActivity: background service wasn't bound in onNewIntent()");
152            return;
153        }
154        final Account account = extractAccount(intent);
155        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
156        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
157        if (sessionId != null) {
158            Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
159            initializeActivityWithRunningRapSession(account, with, sessionId);
160            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
161                Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
162                requestPermissionsAndAcceptCall();
163                resetIntent(intent.getExtras());
164            }
165        } else {
166            throw new IllegalStateException("received onNewIntent without sessionId");
167        }
168    }
169
170    @Override
171    void onBackendConnected() {
172        final Intent intent = getIntent();
173        final Account account = extractAccount(intent);
174        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
175        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
176        if (sessionId != null) {
177            initializeActivityWithRunningRapSession(account, with, sessionId);
178            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
179                Log.d(Config.LOGTAG, "intent action was accept");
180                requestPermissionsAndAcceptCall();
181                resetIntent(intent.getExtras());
182            }
183        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(intent.getAction())) {
184            proposeJingleRtpSession(account, with);
185            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
186        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
187            final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
188            if (extraLastState != null) {
189                Log.d(Config.LOGTAG, "restored last state from intent extra");
190                RtpEndUserState state = RtpEndUserState.valueOf(extraLastState);
191                updateButtonConfiguration(state);
192                updateStateDisplay(state);
193            }
194            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
195        }
196    }
197
198    private void proposeJingleRtpSession(final Account account, final Jid with) {
199        xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with);
200        putScreenInCallMode();
201    }
202
203    @Override
204    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
205        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
206        if (PermissionUtils.allGranted(grantResults)) {
207            if (requestCode == REQUEST_ACCEPT_CALL) {
208                requireRtpConnection().acceptCall();
209            }
210        } else {
211            @StringRes int res;
212            final String firstDenied = getFirstDenied(grantResults, permissions);
213            if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
214                res = R.string.no_microphone_permission;
215            } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
216                res = R.string.no_camera_permission;
217            } else {
218                throw new IllegalStateException("Invalid permission result request");
219            }
220            Toast.makeText(this, res, Toast.LENGTH_SHORT).show();
221        }
222    }
223
224    @Override
225    public void onStop() {
226        releaseWakeLock();
227        //TODO maybe we want to finish if call had ended
228        super.onStop();
229    }
230
231    @Override
232    public void onBackPressed() {
233        endCall();
234        super.onBackPressed();
235    }
236
237
238    private void initializeActivityWithRunningRapSession(final Account account, Jid with, String sessionId) {
239        final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
240                .findJingleRtpConnection(account, with, sessionId);
241        if (reference == null || reference.get() == null) {
242            finish();
243            return;
244        }
245        this.rtpConnectionReference = reference;
246        final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
247        if (currentState == RtpEndUserState.ENDED) {
248            finish();
249            return;
250        }
251        if (currentState == RtpEndUserState.INCOMING_CALL) {
252            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
253        }
254        if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
255            putScreenInCallMode();
256        }
257        binding.with.setText(getWith().getDisplayName());
258        updateStateDisplay(currentState);
259        updateButtonConfiguration(currentState);
260    }
261
262    private void reInitializeActivityWithRunningRapSession(final Account account, Jid with, String sessionId) {
263        runOnUiThread(() -> {
264            initializeActivityWithRunningRapSession(account, with, sessionId);
265        });
266        final Intent intent = new Intent(Intent.ACTION_VIEW);
267        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
268        intent.putExtra(EXTRA_WITH, with.toEscapedString());
269        intent.putExtra(EXTRA_SESSION_ID, sessionId);
270        setIntent(intent);
271    }
272
273    private void updateStateDisplay(final RtpEndUserState state) {
274        switch (state) {
275            case INCOMING_CALL:
276                binding.status.setText(R.string.rtp_state_incoming_call);
277                break;
278            case CONNECTING:
279                binding.status.setText(R.string.rtp_state_connecting);
280                break;
281            case CONNECTED:
282                binding.status.setText(R.string.rtp_state_connected);
283                break;
284            case ACCEPTING_CALL:
285                binding.status.setText(R.string.rtp_state_accepting_call);
286                break;
287            case ENDING_CALL:
288                binding.status.setText(R.string.rtp_state_ending_call);
289                break;
290            case FINDING_DEVICE:
291                binding.status.setText(R.string.rtp_state_finding_device);
292                break;
293            case RINGING:
294                binding.status.setText(R.string.rtp_state_ringing);
295                break;
296            case DECLINED_OR_BUSY:
297                binding.status.setText(R.string.rtp_state_declined_or_busy);
298                break;
299            case CONNECTIVITY_ERROR:
300                binding.status.setText(R.string.rtp_state_connectivity_error);
301                break;
302            case APPLICATION_ERROR:
303                binding.status.setText(R.string.rtp_state_application_failure);
304                break;
305            case ENDED:
306                throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
307            default:
308                throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
309        }
310    }
311
312    @SuppressLint("RestrictedApi")
313    private void updateButtonConfiguration(final RtpEndUserState state) {
314        if (state == RtpEndUserState.INCOMING_CALL) {
315            this.binding.rejectCall.setOnClickListener(this::rejectCall);
316            this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
317            this.binding.rejectCall.setVisibility(View.VISIBLE);
318            this.binding.endCall.setVisibility(View.INVISIBLE);
319            this.binding.acceptCall.setOnClickListener(this::acceptCall);
320            this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
321            this.binding.acceptCall.setVisibility(View.VISIBLE);
322        } else if (state == RtpEndUserState.ENDING_CALL) {
323            this.binding.rejectCall.setVisibility(View.INVISIBLE);
324            this.binding.endCall.setVisibility(View.INVISIBLE);
325            this.binding.acceptCall.setVisibility(View.INVISIBLE);
326        } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
327            this.binding.rejectCall.setVisibility(View.INVISIBLE);
328            this.binding.endCall.setOnClickListener(this::exit);
329            this.binding.endCall.setImageResource(R.drawable.ic_clear_white_48dp);
330            this.binding.endCall.setVisibility(View.VISIBLE);
331            this.binding.acceptCall.setVisibility(View.INVISIBLE);
332        } else if (state == RtpEndUserState.CONNECTIVITY_ERROR || state == RtpEndUserState.APPLICATION_ERROR) {
333            this.binding.rejectCall.setOnClickListener(this::exit);
334            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
335            this.binding.rejectCall.setVisibility(View.VISIBLE);
336            this.binding.endCall.setVisibility(View.INVISIBLE);
337            this.binding.acceptCall.setOnClickListener(this::retry);
338            this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
339            this.binding.acceptCall.setVisibility(View.VISIBLE);
340        } else {
341            this.binding.rejectCall.setVisibility(View.INVISIBLE);
342            this.binding.endCall.setOnClickListener(this::endCall);
343            this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
344            this.binding.endCall.setVisibility(View.VISIBLE);
345            this.binding.acceptCall.setVisibility(View.INVISIBLE);
346        }
347
348        if (state == RtpEndUserState.CONNECTED) {
349            this.binding.inCallActionLeft.setImageResource(R.drawable.ic_volume_off_black_24dp);
350            this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
351            this.binding.inCallActionRight.setImageResource(R.drawable.ic_mic_black_24dp);
352            this.binding.inCallActionRight.setVisibility(View.VISIBLE);
353        } else {
354            this.binding.inCallActionLeft.setVisibility(View.GONE);
355            this.binding.inCallActionRight.setVisibility(View.GONE);
356        }
357    }
358
359    private void retry(View view) {
360        Log.d(Config.LOGTAG, "attempting retry");
361        final Intent intent = getIntent();
362        final Account account = extractAccount(intent);
363        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
364        this.rtpConnectionReference = null;
365        proposeJingleRtpSession(account, with);
366    }
367
368    private void exit(View view) {
369        finish();
370    }
371
372    private Contact getWith() {
373        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
374        final Account account = id.account;
375        return account.getRoster().getContact(id.with);
376    }
377
378    private JingleRtpConnection requireRtpConnection() {
379        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
380        if (connection == null) {
381            throw new IllegalStateException("No RTP connection found");
382        }
383        return connection;
384    }
385
386    @Override
387    public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
388        if (Arrays.asList(RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.DECLINED_OR_BUSY, RtpEndUserState.DECLINED_OR_BUSY).contains(state)) {
389            releaseWakeLock();
390        }
391        Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
392        if (with.isBareJid()) {
393            updateRtpSessionProposalState(account, with, state);
394            return;
395        }
396        if (this.rtpConnectionReference == null) {
397            //this happens when going from proposed session to actual session
398            reInitializeActivityWithRunningRapSession(account, with, sessionId);
399            return;
400        }
401        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
402        if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
403            if (state == RtpEndUserState.ENDED) {
404                finish();
405                return;
406            } else if (asList(RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.DECLINED_OR_BUSY, RtpEndUserState.CONNECTIVITY_ERROR).contains(state)) {
407                resetIntent(account, with, state);
408            }
409            runOnUiThread(() -> {
410                updateStateDisplay(state);
411                updateButtonConfiguration(state);
412            });
413        } else {
414            Log.d(Config.LOGTAG, "received update for other rtp session");
415            //TODO if we only ever have one; we might just switch over? Maybe!
416        }
417    }
418
419    @Override
420    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
421        Log.d(Config.LOGTAG, "onAudioDeviceChanged in activity: selected:" + selectedAudioDevice + ", available:" + availableAudioDevices);
422    }
423
424    private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
425        final Intent currentIntent = getIntent();
426        final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
427        if (withExtra == null) {
428            return;
429        }
430        if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
431            runOnUiThread(() -> {
432                updateStateDisplay(state);
433                updateButtonConfiguration(state);
434            });
435            resetIntent(account, with, state);
436        }
437    }
438
439    private void resetIntent(final Bundle extras) {
440        final Intent intent = new Intent(Intent.ACTION_VIEW);
441        intent.putExtras(extras);
442        setIntent(intent);
443    }
444
445    private void resetIntent(final Account account, Jid with, final RtpEndUserState state) {
446        final Intent intent = new Intent(Intent.ACTION_VIEW);
447        intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
448        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
449        intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
450        setIntent(intent);
451    }
452}