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