123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- /*
- * Nextcloud Talk application
- *
- * @author Mario Danic
- * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- package com.nextcloud.talk.controllers;
- import android.annotation.SuppressLint;
- import android.graphics.Bitmap;
- import android.graphics.drawable.BitmapDrawable;
- import android.media.MediaPlayer;
- import android.net.Uri;
- import android.os.Bundle;
- import android.renderscript.Allocation;
- import android.renderscript.Element;
- import android.renderscript.RenderScript;
- import android.renderscript.ScriptIntrinsicBlur;
- import android.support.annotation.NonNull;
- import android.support.constraint.ConstraintLayout;
- import android.support.v7.graphics.Palette;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.ImageView;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import com.bluelinelabs.conductor.RouterTransaction;
- import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
- import com.bluelinelabs.logansquare.LoganSquare;
- import com.bumptech.glide.load.engine.DiskCacheStrategy;
- import com.bumptech.glide.load.model.GlideUrl;
- import com.bumptech.glide.load.model.LazyHeaders;
- import com.bumptech.glide.load.resource.bitmap.CircleCrop;
- import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
- import com.bumptech.glide.request.RequestOptions;
- import com.bumptech.glide.request.target.SimpleTarget;
- import com.bumptech.glide.request.transition.Transition;
- import com.nextcloud.talk.R;
- import com.nextcloud.talk.api.NcApi;
- import com.nextcloud.talk.application.NextcloudTalkApplication;
- import com.nextcloud.talk.controllers.base.BaseController;
- import com.nextcloud.talk.events.ConfigurationChangeEvent;
- import com.nextcloud.talk.models.RingtoneSettings;
- import com.nextcloud.talk.models.database.UserEntity;
- import com.nextcloud.talk.models.json.participants.Participant;
- import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
- import com.nextcloud.talk.models.json.rooms.Room;
- import com.nextcloud.talk.models.json.rooms.RoomsOverall;
- import com.nextcloud.talk.utils.ApiUtils;
- import com.nextcloud.talk.utils.MagicFlipView;
- import com.nextcloud.talk.utils.bundle.BundleKeys;
- import com.nextcloud.talk.utils.glide.GlideApp;
- import com.nextcloud.talk.utils.preferences.AppPreferences;
- import com.nextcloud.talk.utils.singletons.AvatarStatusCodeHolder;
- import org.greenrobot.eventbus.EventBus;
- import org.greenrobot.eventbus.Subscribe;
- import org.greenrobot.eventbus.ThreadMode;
- import org.parceler.Parcels;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.inject.Inject;
- import autodagger.AutoInjector;
- import butterknife.BindView;
- import butterknife.OnClick;
- import io.reactivex.Observer;
- import io.reactivex.android.schedulers.AndroidSchedulers;
- import io.reactivex.disposables.Disposable;
- import io.reactivex.schedulers.Schedulers;
- import okhttp3.Cache;
- @AutoInjector(NextcloudTalkApplication.class)
- public class CallNotificationController extends BaseController {
- private static final String TAG = "CallNotificationController";
- @Inject
- NcApi ncApi;
- @Inject
- AppPreferences appPreferences;
- @Inject
- EventBus eventBus;
- @BindView(R.id.conversationNameTextView)
- TextView conversationNameTextView;
- @BindView(R.id.avatarImageView)
- ImageView avatarImageView;
- @BindView(R.id.callAnswerVoiceOnlyView)
- MagicFlipView callAnswerVoiceOnlyView;
- @BindView(R.id.callAnswerCameraView)
- MagicFlipView callAnswerCameraView;
- @BindView(R.id.constraintLayout)
- ConstraintLayout constraintLayout;
- @BindView(R.id.incomingTextRelativeLayout)
- RelativeLayout incomingTextRelativeLayout;
- @Inject
- Cache cache;
- private List<Disposable> disposablesList = new ArrayList<>();
- private Bundle originalBundle;
- private String roomId;
- private UserEntity userBeingCalled;
- private String credentials;
- private Room currentRoom;
- private MediaPlayer mediaPlayer;
- private boolean leavingScreen = false;
- private RenderScript renderScript;
- public CallNotificationController(Bundle args) {
- super(args);
- NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
- this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
- this.currentRoom = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ROOM));
- this.userBeingCalled = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
- this.originalBundle = args;
- credentials = ApiUtils.getCredentials(userBeingCalled.getUserId(), userBeingCalled.getToken());
- }
- @Override
- protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
- return inflater.inflate(R.layout.controller_call_notification, container, false);
- }
- private void showAnswerControls() {
- callAnswerCameraView.setVisibility(View.VISIBLE);
- callAnswerVoiceOnlyView.setVisibility(View.VISIBLE);
- }
- @OnClick(R.id.callControlHangupView)
- void hangup() {
- leavingScreen = true;
- if (getActivity() != null) {
- getActivity().finish();
- }
- }
- @OnClick(R.id.callAnswerCameraView)
- void answerWithCamera() {
- originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
- proceedToCall();
- }
- @OnClick(R.id.callAnswerVoiceOnlyView)
- void answerVoiceOnly() {
- originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
- proceedToCall();
- }
- private void proceedToCall() {
- originalBundle.putString(BundleKeys.KEY_ROOM_TOKEN, currentRoom.getToken());
- getRouter().setRoot(RouterTransaction.with(new CallController(originalBundle))
- .popChangeHandler(new HorizontalChangeHandler())
- .pushChangeHandler(new HorizontalChangeHandler()));
- }
- private void checkIfAnyParticipantsRemainInRoom() {
- ncApi.getPeersForCall(credentials, ApiUtils.getUrlForParticipants(userBeingCalled.getBaseUrl(),
- currentRoom.getToken()))
- .subscribeOn(Schedulers.newThread())
- .takeWhile(observable -> !leavingScreen)
- .retry(3)
- .subscribe(new Observer<ParticipantsOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- disposablesList.add(d);
- }
- @Override
- public void onNext(ParticipantsOverall participantsOverall) {
- boolean hasParticipantsInCall = false;
- boolean inCallOnDifferentDevice = false;
- List<Participant> participantList = participantsOverall.getOcs().getData();
- for (Participant participant : participantList) {
- if (participant.isInCall()) {
- hasParticipantsInCall = true;
- if (participant.getUserId().equals(userBeingCalled.getUserId())) {
- inCallOnDifferentDevice = true;
- break;
- }
- }
- }
- if (!hasParticipantsInCall || inCallOnDifferentDevice) {
- if (getActivity() != null) {
- getActivity().runOnUiThread(() -> hangup());
- }
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- if (!leavingScreen) {
- checkIfAnyParticipantsRemainInRoom();
- }
- }
- });
- }
- private void handleFromNotification() {
- ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(userBeingCalled.getBaseUrl()))
- .subscribeOn(Schedulers.newThread())
- .retry(3)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<RoomsOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- disposablesList.add(d);
- }
- @Override
- public void onNext(RoomsOverall roomsOverall) {
- for (Room room : roomsOverall.getOcs().getData()) {
- if (roomId.equals(room.getRoomId())) {
- currentRoom = room;
- runAllThings();
- break;
- }
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void runAllThings() {
- if (conversationNameTextView != null) {
- conversationNameTextView.setText(currentRoom.getDisplayName());
- }
- loadAvatar();
- checkIfAnyParticipantsRemainInRoom();
- showAnswerControls();
- }
- @SuppressLint("LongLogTag")
- @Override
- protected void onViewBound(@NonNull View view) {
- super.onViewBound(view);
- renderScript = RenderScript.create(getActivity());
- try {
- cache.evictAll();
- } catch (IOException e) {
- Log.e(TAG, "Failed to evict cache");
- }
- if (currentRoom == null) {
- handleFromNotification();
- } else {
- runAllThings();
- }
- String callRingtonePreferenceString = appPreferences.getCallRingtoneUri();
- Uri ringtoneUri;
- if (TextUtils.isEmpty(callRingtonePreferenceString)) {
- // play default sound
- ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName()+
- "/raw/librem_by_feandesign_call");
- } else {
- try {
- RingtoneSettings ringtoneSettings = LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
- ringtoneUri = ringtoneSettings.getRingtoneUri();
- } catch (IOException e) {
- Log.e(TAG, "Failed to parse ringtone settings");
- ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName()+
- "/raw/librem_by_feandesign_call");
- }
- }
- if (ringtoneUri != null) {
- mediaPlayer = MediaPlayer.create(getApplicationContext(), ringtoneUri);
- mediaPlayer.setLooping(true);
- mediaPlayer.start();
- }
- }
- @Subscribe(threadMode = ThreadMode.MAIN)
- public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
- ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) avatarImageView.getLayoutParams();
- int dimen = (int) getResources().getDimension(R.dimen.avatar_size_very_big);
- layoutParams.width = dimen;
- layoutParams.height = dimen;
- avatarImageView.setLayoutParams(layoutParams);
- }
- @Override
- protected void onDetach(@NonNull View view) {
- super.onDetach(view);
- eventBus.unregister(this);
- }
- @Override
- protected void onAttach(@NonNull View view) {
- super.onAttach(view);
- eventBus.register(this);
- }
- private void loadAvatar() {
- int avatarSize = Math.round(NextcloudTalkApplication
- .getSharedApplication().getResources().getDimension(R.dimen.avatar_fetching_size_very_big));
- switch (currentRoom.getType()) {
- case ROOM_TYPE_ONE_TO_ONE_CALL:
- avatarImageView.setVisibility(View.VISIBLE);
- GlideUrl glideUrl = new GlideUrl(ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
- currentRoom.getName(), R.dimen.avatar_size_very_big), new LazyHeaders.Builder()
- .setHeader("Accept", "image/*")
- .setHeader("User-Agent", ApiUtils.getUserAgent())
- .build());
- GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
- .asBitmap()
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .load(glideUrl)
- .centerInside()
- .override(avatarSize, avatarSize)
- .into(new SimpleTarget<Bitmap>() {
- @Override
- public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
- if (getActivity() != null) {
- avatarImageView.setImageBitmap(TransformationUtils.circleCrop(GlideApp.get
- (getActivity()).getBitmapPool(), resource, avatarSize, avatarSize));
- }
- if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 200) {
- final Allocation input = Allocation.createFromBitmap(renderScript, resource);
- final Allocation output = Allocation.createTyped(renderScript, input.getType());
- final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element
- .U8_4(renderScript));
- script.setRadius(15f);
- script.setInput(input);
- script.forEach(output);
- output.copyTo(resource);
- incomingTextRelativeLayout.setBackground(getResources().getDrawable(R.drawable
- .incoming_gradient));
- constraintLayout.setBackground(new BitmapDrawable(resource));
- } else if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 201) {
- Palette palette = Palette.from(resource).generate();
- constraintLayout.setBackgroundColor(palette.getDominantColor(
- getResources().getColor(R.color.grey950)));
- }
- }
- });
- break;
- case ROOM_GROUP_CALL:
- GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
- .asBitmap()
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .load(R.drawable.ic_group_white_24px)
- .centerInside()
- .override(avatarSize, avatarSize)
- .apply(RequestOptions.bitmapTransform(new CircleCrop()))
- .into(avatarImageView);
- case ROOM_PUBLIC_CALL:
- GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
- .asBitmap()
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .load(R.drawable.ic_link_white_24px)
- .centerInside()
- .override(avatarSize, avatarSize)
- .apply(RequestOptions.bitmapTransform(new CircleCrop()))
- .into(avatarImageView);
- break;
- default:
- }
- }
- private void endMediaPlayer() {
- if (mediaPlayer != null) {
- if (mediaPlayer.isPlaying()) {
- mediaPlayer.stop();
- }
- mediaPlayer.release();
- mediaPlayer = null;
- }
- }
- @Override
- public void onDestroy() {
- AvatarStatusCodeHolder.getInstance().setStatusCode(0);
- leavingScreen = true;
- dispose();
- endMediaPlayer();
- super.onDestroy();
- }
- private void dispose() {
- Disposable disposable;
- for (int i = 0; i < disposablesList.size(); i++) {
- if ((disposable = disposablesList.get(i)).isDisposed()) {
- disposable.dispose();
- }
- }
- }
- }
|