RtpSessionActivity.java

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