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            this.mProximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
119            if (!this.mProximityWakeLock.isHeld()) {
120                Log.d(Config.LOGTAG, "acquiring wake lock");
121                this.mProximityWakeLock.acquire();
122            }
123        }
124    }
125
126    private void releaseWakeLock() {
127        if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
128            Log.d(Config.LOGTAG, "releasing wake lock");
129            this.mProximityWakeLock.release();
130            this.mProximityWakeLock = null;
131        }
132    }
133
134    @Override
135    protected void refreshUiReal() {
136
137    }
138
139    @Override
140    public void onNewIntent(final Intent intent) {
141        super.onNewIntent(intent);
142        final Account account = extractAccount(intent);
143        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
144        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
145        if (sessionId != null) {
146            Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
147            initializeActivityWithRunningRapSession(account, with, sessionId);
148            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
149                Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
150                requestPermissionsAndAcceptCall();
151                resetIntent(intent.getExtras());
152            }
153        } else {
154            throw new IllegalStateException("received onNewIntent without sessionId");
155        }
156    }
157
158    @Override
159    void onBackendConnected() {
160        final Intent intent = getIntent();
161        final Account account = extractAccount(intent);
162        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
163        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
164        if (sessionId != null) {
165            initializeActivityWithRunningRapSession(account, with, sessionId);
166            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
167                Log.d(Config.LOGTAG, "intent action was accept");
168                requestPermissionsAndAcceptCall();
169                resetIntent(intent.getExtras());
170            }
171        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(intent.getAction())) {
172            proposeJingleRtpSession(account, with);
173            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
174        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
175            final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
176            if (extraLastState != null) {
177                Log.d(Config.LOGTAG, "restored last state from intent extra");
178                RtpEndUserState state = RtpEndUserState.valueOf(extraLastState);
179                updateButtonConfiguration(state);
180                updateStateDisplay(state);
181            }
182            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
183        }
184    }
185
186    private void proposeJingleRtpSession(final Account account, final Jid with) {
187        xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with);
188        putScreenInCallMode();
189    }
190
191    @Override
192    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
193        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
194        if (PermissionUtils.allGranted(grantResults)) {
195            if (requestCode == REQUEST_ACCEPT_CALL) {
196                requireRtpConnection().acceptCall();
197            }
198        } else {
199            @StringRes int res;
200            final String firstDenied = getFirstDenied(grantResults, permissions);
201            if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
202                res = R.string.no_microphone_permission;
203            } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
204                res = R.string.no_camera_permission;
205            } else {
206                throw new IllegalStateException("Invalid permission result request");
207            }
208            Toast.makeText(this, res, Toast.LENGTH_SHORT).show();
209        }
210    }
211
212    @Override
213    public void onStop() {
214        if (!isChangingConfigurations()) {
215            releaseWakeLock();
216        }
217        super.onStop();
218    }
219
220    @Override
221    public void onBackPressed() {
222        endCall();
223        super.onBackPressed();
224    }
225
226
227    private void initializeActivityWithRunningRapSession(final Account account, Jid with, String sessionId) {
228        final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
229                .findJingleRtpConnection(account, with, sessionId);
230        if (reference == null || reference.get() == null) {
231            finish();
232            return;
233        }
234        this.rtpConnectionReference = reference;
235        final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
236        if (currentState == RtpEndUserState.ENDED) {
237            finish();
238            return;
239        }
240        if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
241            putScreenInCallMode();
242        }
243        binding.with.setText(getWith().getDisplayName());
244        updateStateDisplay(currentState);
245        updateButtonConfiguration(currentState);
246    }
247
248    private void reInitializeActivityWithRunningRapSession(final Account account, Jid with, String sessionId) {
249        runOnUiThread(() -> {
250            initializeActivityWithRunningRapSession(account, with, sessionId);
251        });
252        final Intent intent = new Intent(Intent.ACTION_VIEW);
253        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
254        intent.putExtra(EXTRA_WITH, with.toEscapedString());
255        intent.putExtra(EXTRA_SESSION_ID, sessionId);
256        setIntent(intent);
257    }
258
259    private void updateStateDisplay(final RtpEndUserState state) {
260        switch (state) {
261            case INCOMING_CALL:
262                binding.status.setText(R.string.rtp_state_incoming_call);
263                break;
264            case CONNECTING:
265                binding.status.setText(R.string.rtp_state_connecting);
266                break;
267            case CONNECTED:
268                binding.status.setText(R.string.rtp_state_connected);
269                break;
270            case ACCEPTING_CALL:
271                binding.status.setText(R.string.rtp_state_accepting_call);
272                break;
273            case ENDING_CALL:
274                binding.status.setText(R.string.rtp_state_ending_call);
275                break;
276            case FINDING_DEVICE:
277                binding.status.setText(R.string.rtp_state_finding_device);
278                break;
279            case RINGING:
280                binding.status.setText(R.string.rtp_state_ringing);
281                break;
282            case DECLINED_OR_BUSY:
283                binding.status.setText(R.string.rtp_state_declined_or_busy);
284                break;
285            case CONNECTIVITY_ERROR:
286                binding.status.setText(R.string.rtp_state_connectivity_error);
287                break;
288            case APPLICATION_ERROR:
289                binding.status.setText(R.string.rtp_state_application_failure);
290                break;
291            case ENDED:
292                throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
293            default:
294                throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
295        }
296    }
297
298    @SuppressLint("RestrictedApi")
299    private void updateButtonConfiguration(final RtpEndUserState state) {
300        if (state == RtpEndUserState.INCOMING_CALL) {
301            this.binding.rejectCall.setOnClickListener(this::rejectCall);
302            this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
303            this.binding.rejectCall.setVisibility(View.VISIBLE);
304            this.binding.endCall.setVisibility(View.INVISIBLE);
305            this.binding.acceptCall.setOnClickListener(this::acceptCall);
306            this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
307            this.binding.acceptCall.setVisibility(View.VISIBLE);
308        } else if (state == RtpEndUserState.ENDING_CALL) {
309            this.binding.rejectCall.setVisibility(View.INVISIBLE);
310            this.binding.endCall.setVisibility(View.INVISIBLE);
311            this.binding.acceptCall.setVisibility(View.INVISIBLE);
312        } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
313            this.binding.rejectCall.setVisibility(View.INVISIBLE);
314            this.binding.endCall.setOnClickListener(this::exit);
315            this.binding.endCall.setImageResource(R.drawable.ic_clear_white_48dp);
316            this.binding.endCall.setVisibility(View.VISIBLE);
317            this.binding.acceptCall.setVisibility(View.INVISIBLE);
318        } else if (state == RtpEndUserState.CONNECTIVITY_ERROR || state == RtpEndUserState.APPLICATION_ERROR) {
319            this.binding.rejectCall.setOnClickListener(this::exit);
320            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
321            this.binding.rejectCall.setVisibility(View.VISIBLE);
322            this.binding.endCall.setVisibility(View.INVISIBLE);
323            this.binding.acceptCall.setOnClickListener(this::retry);
324            this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
325            this.binding.acceptCall.setVisibility(View.VISIBLE);
326        } else {
327            this.binding.rejectCall.setVisibility(View.INVISIBLE);
328            this.binding.endCall.setOnClickListener(this::endCall);
329            this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
330            this.binding.endCall.setVisibility(View.VISIBLE);
331            this.binding.acceptCall.setVisibility(View.INVISIBLE);
332        }
333    }
334
335    private void retry(View view) {
336        Log.d(Config.LOGTAG, "attempting retry");
337        final Intent intent = getIntent();
338        final Account account = extractAccount(intent);
339        final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
340        this.rtpConnectionReference = null;
341        proposeJingleRtpSession(account, with);
342    }
343
344    private void exit(View view) {
345        finish();
346    }
347
348    private Contact getWith() {
349        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
350        final Account account = id.account;
351        return account.getRoster().getContact(id.with);
352    }
353
354    private JingleRtpConnection requireRtpConnection() {
355        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
356        if (connection == null) {
357            throw new IllegalStateException("No RTP connection found");
358        }
359        return connection;
360    }
361
362    @Override
363    public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
364        if (Arrays.asList(RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.DECLINED_OR_BUSY, RtpEndUserState.DECLINED_OR_BUSY).contains(state)) {
365            releaseWakeLock();
366        }
367        Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
368        if (with.isBareJid()) {
369            updateRtpSessionProposalState(account, with, state);
370            return;
371        }
372        if (this.rtpConnectionReference == null) {
373            //this happens when going from proposed session to actual session
374            reInitializeActivityWithRunningRapSession(account, with, sessionId);
375            return;
376        }
377        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
378        if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
379            if (state == RtpEndUserState.ENDED) {
380                finish();
381                return;
382            } else if (asList(RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.DECLINED_OR_BUSY, RtpEndUserState.CONNECTIVITY_ERROR).contains(state)) {
383                resetIntent(account, with, state);
384            }
385            runOnUiThread(() -> {
386                updateStateDisplay(state);
387                updateButtonConfiguration(state);
388            });
389        } else {
390            Log.d(Config.LOGTAG, "received update for other rtp session");
391            //TODO if we only ever have one; we might just switch over? Maybe!
392        }
393    }
394
395    private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
396        final Intent currentIntent = getIntent();
397        final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
398        if (withExtra == null) {
399            return;
400        }
401        if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
402            runOnUiThread(() -> {
403                updateStateDisplay(state);
404                updateButtonConfiguration(state);
405            });
406            resetIntent(account, with, state);
407        }
408    }
409
410    private void resetIntent(final Bundle extras) {
411        final Intent intent = new Intent(Intent.ACTION_VIEW);
412        intent.putExtras(extras);
413        setIntent(intent);
414    }
415
416    private void resetIntent(final Account account, Jid with, final RtpEndUserState state) {
417        final Intent intent = new Intent(Intent.ACTION_VIEW);
418        intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
419        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
420        intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
421        setIntent(intent);
422    }
423}