CallNotificationController.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.controllers;
  21. import android.annotation.SuppressLint;
  22. import android.graphics.Bitmap;
  23. import android.graphics.drawable.BitmapDrawable;
  24. import android.media.MediaPlayer;
  25. import android.net.Uri;
  26. import android.os.Bundle;
  27. import android.renderscript.Allocation;
  28. import android.renderscript.Element;
  29. import android.renderscript.RenderScript;
  30. import android.renderscript.ScriptIntrinsicBlur;
  31. import android.support.annotation.NonNull;
  32. import android.support.constraint.ConstraintLayout;
  33. import android.support.v7.graphics.Palette;
  34. import android.text.TextUtils;
  35. import android.util.Log;
  36. import android.view.LayoutInflater;
  37. import android.view.View;
  38. import android.view.ViewGroup;
  39. import android.widget.ImageView;
  40. import android.widget.RelativeLayout;
  41. import android.widget.TextView;
  42. import com.bluelinelabs.conductor.RouterTransaction;
  43. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  44. import com.bluelinelabs.logansquare.LoganSquare;
  45. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  46. import com.bumptech.glide.load.model.GlideUrl;
  47. import com.bumptech.glide.load.model.LazyHeaders;
  48. import com.bumptech.glide.load.resource.bitmap.CircleCrop;
  49. import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
  50. import com.bumptech.glide.request.RequestOptions;
  51. import com.bumptech.glide.request.target.SimpleTarget;
  52. import com.bumptech.glide.request.transition.Transition;
  53. import com.nextcloud.talk.R;
  54. import com.nextcloud.talk.api.NcApi;
  55. import com.nextcloud.talk.application.NextcloudTalkApplication;
  56. import com.nextcloud.talk.controllers.base.BaseController;
  57. import com.nextcloud.talk.events.ConfigurationChangeEvent;
  58. import com.nextcloud.talk.models.RingtoneSettings;
  59. import com.nextcloud.talk.models.database.UserEntity;
  60. import com.nextcloud.talk.models.json.participants.Participant;
  61. import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
  62. import com.nextcloud.talk.models.json.rooms.Room;
  63. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  64. import com.nextcloud.talk.utils.ApiUtils;
  65. import com.nextcloud.talk.utils.MagicFlipView;
  66. import com.nextcloud.talk.utils.bundle.BundleKeys;
  67. import com.nextcloud.talk.utils.glide.GlideApp;
  68. import com.nextcloud.talk.utils.preferences.AppPreferences;
  69. import com.nextcloud.talk.utils.singletons.AvatarStatusCodeHolder;
  70. import org.greenrobot.eventbus.EventBus;
  71. import org.greenrobot.eventbus.Subscribe;
  72. import org.greenrobot.eventbus.ThreadMode;
  73. import org.parceler.Parcels;
  74. import java.io.IOException;
  75. import java.util.ArrayList;
  76. import java.util.List;
  77. import javax.inject.Inject;
  78. import autodagger.AutoInjector;
  79. import butterknife.BindView;
  80. import butterknife.OnClick;
  81. import io.reactivex.Observer;
  82. import io.reactivex.android.schedulers.AndroidSchedulers;
  83. import io.reactivex.disposables.Disposable;
  84. import io.reactivex.schedulers.Schedulers;
  85. import okhttp3.Cache;
  86. @AutoInjector(NextcloudTalkApplication.class)
  87. public class CallNotificationController extends BaseController {
  88. private static final String TAG = "CallNotificationController";
  89. @Inject
  90. NcApi ncApi;
  91. @Inject
  92. AppPreferences appPreferences;
  93. @Inject
  94. EventBus eventBus;
  95. @BindView(R.id.conversationNameTextView)
  96. TextView conversationNameTextView;
  97. @BindView(R.id.avatarImageView)
  98. ImageView avatarImageView;
  99. @BindView(R.id.callAnswerVoiceOnlyView)
  100. MagicFlipView callAnswerVoiceOnlyView;
  101. @BindView(R.id.callAnswerCameraView)
  102. MagicFlipView callAnswerCameraView;
  103. @BindView(R.id.constraintLayout)
  104. ConstraintLayout constraintLayout;
  105. @BindView(R.id.incomingTextRelativeLayout)
  106. RelativeLayout incomingTextRelativeLayout;
  107. @Inject
  108. Cache cache;
  109. private List<Disposable> disposablesList = new ArrayList<>();
  110. private Bundle originalBundle;
  111. private String roomId;
  112. private UserEntity userBeingCalled;
  113. private String credentials;
  114. private Room currentRoom;
  115. private MediaPlayer mediaPlayer;
  116. private boolean leavingScreen = false;
  117. private RenderScript renderScript;
  118. public CallNotificationController(Bundle args) {
  119. super(args);
  120. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  121. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  122. this.currentRoom = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ROOM));
  123. this.userBeingCalled = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  124. this.originalBundle = args;
  125. credentials = ApiUtils.getCredentials(userBeingCalled.getUserId(), userBeingCalled.getToken());
  126. }
  127. @Override
  128. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  129. return inflater.inflate(R.layout.controller_call_notification, container, false);
  130. }
  131. private void showAnswerControls() {
  132. callAnswerCameraView.setVisibility(View.VISIBLE);
  133. callAnswerVoiceOnlyView.setVisibility(View.VISIBLE);
  134. }
  135. @OnClick(R.id.callControlHangupView)
  136. void hangup() {
  137. leavingScreen = true;
  138. if (getActivity() != null) {
  139. getActivity().finish();
  140. }
  141. }
  142. @OnClick(R.id.callAnswerCameraView)
  143. void answerWithCamera() {
  144. originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  145. proceedToCall();
  146. }
  147. @OnClick(R.id.callAnswerVoiceOnlyView)
  148. void answerVoiceOnly() {
  149. originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  150. proceedToCall();
  151. }
  152. private void proceedToCall() {
  153. originalBundle.putString(BundleKeys.KEY_ROOM_TOKEN, currentRoom.getToken());
  154. getRouter().setRoot(RouterTransaction.with(new CallController(originalBundle))
  155. .popChangeHandler(new HorizontalChangeHandler())
  156. .pushChangeHandler(new HorizontalChangeHandler()));
  157. }
  158. private void checkIfAnyParticipantsRemainInRoom() {
  159. ncApi.getPeersForCall(credentials, ApiUtils.getUrlForParticipants(userBeingCalled.getBaseUrl(),
  160. currentRoom.getToken()))
  161. .subscribeOn(Schedulers.newThread())
  162. .takeWhile(observable -> !leavingScreen)
  163. .retry(3)
  164. .subscribe(new Observer<ParticipantsOverall>() {
  165. @Override
  166. public void onSubscribe(Disposable d) {
  167. disposablesList.add(d);
  168. }
  169. @Override
  170. public void onNext(ParticipantsOverall participantsOverall) {
  171. boolean hasParticipantsInCall = false;
  172. boolean inCallOnDifferentDevice = false;
  173. List<Participant> participantList = participantsOverall.getOcs().getData();
  174. for (Participant participant : participantList) {
  175. if (participant.isInCall()) {
  176. hasParticipantsInCall = true;
  177. if (participant.getUserId().equals(userBeingCalled.getUserId())) {
  178. inCallOnDifferentDevice = true;
  179. break;
  180. }
  181. }
  182. }
  183. if (!hasParticipantsInCall || inCallOnDifferentDevice) {
  184. if (getActivity() != null) {
  185. getActivity().runOnUiThread(() -> hangup());
  186. }
  187. }
  188. }
  189. @Override
  190. public void onError(Throwable e) {
  191. }
  192. @Override
  193. public void onComplete() {
  194. if (!leavingScreen) {
  195. checkIfAnyParticipantsRemainInRoom();
  196. }
  197. }
  198. });
  199. }
  200. private void handleFromNotification() {
  201. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(userBeingCalled.getBaseUrl()))
  202. .subscribeOn(Schedulers.newThread())
  203. .retry(3)
  204. .observeOn(AndroidSchedulers.mainThread())
  205. .subscribe(new Observer<RoomsOverall>() {
  206. @Override
  207. public void onSubscribe(Disposable d) {
  208. disposablesList.add(d);
  209. }
  210. @Override
  211. public void onNext(RoomsOverall roomsOverall) {
  212. for (Room room : roomsOverall.getOcs().getData()) {
  213. if (roomId.equals(room.getRoomId())) {
  214. currentRoom = room;
  215. runAllThings();
  216. break;
  217. }
  218. }
  219. }
  220. @Override
  221. public void onError(Throwable e) {
  222. }
  223. @Override
  224. public void onComplete() {
  225. }
  226. });
  227. }
  228. private void runAllThings() {
  229. if (conversationNameTextView != null) {
  230. conversationNameTextView.setText(currentRoom.getDisplayName());
  231. }
  232. loadAvatar();
  233. checkIfAnyParticipantsRemainInRoom();
  234. showAnswerControls();
  235. }
  236. @SuppressLint("LongLogTag")
  237. @Override
  238. protected void onViewBound(@NonNull View view) {
  239. super.onViewBound(view);
  240. renderScript = RenderScript.create(getActivity());
  241. try {
  242. cache.evictAll();
  243. } catch (IOException e) {
  244. Log.e(TAG, "Failed to evict cache");
  245. }
  246. if (currentRoom == null) {
  247. handleFromNotification();
  248. } else {
  249. runAllThings();
  250. }
  251. String callRingtonePreferenceString = appPreferences.getCallRingtoneUri();
  252. Uri ringtoneUri;
  253. if (TextUtils.isEmpty(callRingtonePreferenceString)) {
  254. // play default sound
  255. ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName()+
  256. "/raw/librem_by_feandesign_call");
  257. } else {
  258. try {
  259. RingtoneSettings ringtoneSettings = LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
  260. ringtoneUri = ringtoneSettings.getRingtoneUri();
  261. } catch (IOException e) {
  262. Log.e(TAG, "Failed to parse ringtone settings");
  263. ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName()+
  264. "/raw/librem_by_feandesign_call");
  265. }
  266. }
  267. if (ringtoneUri != null) {
  268. mediaPlayer = MediaPlayer.create(getApplicationContext(), ringtoneUri);
  269. mediaPlayer.setLooping(true);
  270. mediaPlayer.start();
  271. }
  272. }
  273. @Subscribe(threadMode = ThreadMode.MAIN)
  274. public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
  275. ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) avatarImageView.getLayoutParams();
  276. int dimen = (int) getResources().getDimension(R.dimen.avatar_size_very_big);
  277. layoutParams.width = dimen;
  278. layoutParams.height = dimen;
  279. avatarImageView.setLayoutParams(layoutParams);
  280. }
  281. @Override
  282. protected void onDetach(@NonNull View view) {
  283. super.onDetach(view);
  284. eventBus.unregister(this);
  285. }
  286. @Override
  287. protected void onAttach(@NonNull View view) {
  288. super.onAttach(view);
  289. eventBus.register(this);
  290. }
  291. private void loadAvatar() {
  292. int avatarSize = Math.round(NextcloudTalkApplication
  293. .getSharedApplication().getResources().getDimension(R.dimen.avatar_fetching_size_very_big));
  294. switch (currentRoom.getType()) {
  295. case ROOM_TYPE_ONE_TO_ONE_CALL:
  296. avatarImageView.setVisibility(View.VISIBLE);
  297. GlideUrl glideUrl = new GlideUrl(ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
  298. currentRoom.getName(), R.dimen.avatar_size_very_big), new LazyHeaders.Builder()
  299. .setHeader("Accept", "image/*")
  300. .setHeader("User-Agent", ApiUtils.getUserAgent())
  301. .build());
  302. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  303. .asBitmap()
  304. .diskCacheStrategy(DiskCacheStrategy.NONE)
  305. .load(glideUrl)
  306. .centerInside()
  307. .override(avatarSize, avatarSize)
  308. .into(new SimpleTarget<Bitmap>() {
  309. @Override
  310. public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
  311. if (getActivity() != null) {
  312. avatarImageView.setImageBitmap(TransformationUtils.circleCrop(GlideApp.get
  313. (getActivity()).getBitmapPool(), resource, avatarSize, avatarSize));
  314. }
  315. if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 200) {
  316. final Allocation input = Allocation.createFromBitmap(renderScript, resource);
  317. final Allocation output = Allocation.createTyped(renderScript, input.getType());
  318. final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element
  319. .U8_4(renderScript));
  320. script.setRadius(15f);
  321. script.setInput(input);
  322. script.forEach(output);
  323. output.copyTo(resource);
  324. incomingTextRelativeLayout.setBackground(getResources().getDrawable(R.drawable
  325. .incoming_gradient));
  326. constraintLayout.setBackground(new BitmapDrawable(resource));
  327. } else if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 201) {
  328. Palette palette = Palette.from(resource).generate();
  329. constraintLayout.setBackgroundColor(palette.getDominantColor(
  330. getResources().getColor(R.color.grey950)));
  331. }
  332. }
  333. });
  334. break;
  335. case ROOM_GROUP_CALL:
  336. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  337. .asBitmap()
  338. .diskCacheStrategy(DiskCacheStrategy.NONE)
  339. .load(R.drawable.ic_group_white_24px)
  340. .centerInside()
  341. .override(avatarSize, avatarSize)
  342. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  343. .into(avatarImageView);
  344. case ROOM_PUBLIC_CALL:
  345. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  346. .asBitmap()
  347. .diskCacheStrategy(DiskCacheStrategy.NONE)
  348. .load(R.drawable.ic_link_white_24px)
  349. .centerInside()
  350. .override(avatarSize, avatarSize)
  351. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  352. .into(avatarImageView);
  353. break;
  354. default:
  355. }
  356. }
  357. private void endMediaPlayer() {
  358. if (mediaPlayer != null) {
  359. if (mediaPlayer.isPlaying()) {
  360. mediaPlayer.stop();
  361. }
  362. mediaPlayer.release();
  363. mediaPlayer = null;
  364. }
  365. }
  366. @Override
  367. public void onDestroy() {
  368. AvatarStatusCodeHolder.getInstance().setStatusCode(0);
  369. leavingScreen = true;
  370. dispose();
  371. endMediaPlayer();
  372. super.onDestroy();
  373. }
  374. private void dispose() {
  375. Disposable disposable;
  376. for (int i = 0; i < disposablesList.size(); i++) {
  377. if ((disposable = disposablesList.get(i)).isDisposed()) {
  378. disposable.dispose();
  379. }
  380. }
  381. }
  382. }