CallNotificationController.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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.content.Context;
  23. import android.graphics.Bitmap;
  24. import android.graphics.Color;
  25. import android.graphics.drawable.BitmapDrawable;
  26. import android.graphics.drawable.ColorDrawable;
  27. import android.media.AudioAttributes;
  28. import android.media.MediaPlayer;
  29. import android.net.Uri;
  30. import android.os.Build;
  31. import android.os.Bundle;
  32. import android.os.Handler;
  33. import android.os.VibrationEffect;
  34. import android.os.Vibrator;
  35. import android.renderscript.Allocation;
  36. import android.renderscript.Element;
  37. import android.renderscript.RenderScript;
  38. import android.renderscript.ScriptIntrinsicBlur;
  39. import android.text.TextUtils;
  40. import android.util.Log;
  41. import android.view.LayoutInflater;
  42. import android.view.View;
  43. import android.view.ViewGroup;
  44. import android.widget.ImageView;
  45. import android.widget.RelativeLayout;
  46. import android.widget.TextView;
  47. import com.bluelinelabs.conductor.RouterTransaction;
  48. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  49. import com.bluelinelabs.logansquare.LoganSquare;
  50. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  51. import com.bumptech.glide.load.model.GlideUrl;
  52. import com.bumptech.glide.load.model.LazyHeaders;
  53. import com.bumptech.glide.load.resource.bitmap.CircleCrop;
  54. import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
  55. import com.bumptech.glide.request.RequestOptions;
  56. import com.bumptech.glide.request.target.SimpleTarget;
  57. import com.bumptech.glide.request.transition.Transition;
  58. import com.nextcloud.talk.R;
  59. import com.nextcloud.talk.api.NcApi;
  60. import com.nextcloud.talk.application.NextcloudTalkApplication;
  61. import com.nextcloud.talk.controllers.base.BaseController;
  62. import com.nextcloud.talk.events.ConfigurationChangeEvent;
  63. import com.nextcloud.talk.models.RingtoneSettings;
  64. import com.nextcloud.talk.models.database.UserEntity;
  65. import com.nextcloud.talk.models.json.participants.Participant;
  66. import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
  67. import com.nextcloud.talk.models.json.rooms.Conversation;
  68. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  69. import com.nextcloud.talk.utils.ApiUtils;
  70. import com.nextcloud.talk.utils.DoNotDisturbUtils;
  71. import com.nextcloud.talk.utils.MagicFlipView;
  72. import com.nextcloud.talk.utils.bundle.BundleKeys;
  73. import com.nextcloud.talk.utils.glide.GlideApp;
  74. import com.nextcloud.talk.utils.preferences.AppPreferences;
  75. import com.nextcloud.talk.utils.singletons.AvatarStatusCodeHolder;
  76. import org.greenrobot.eventbus.EventBus;
  77. import org.greenrobot.eventbus.Subscribe;
  78. import org.greenrobot.eventbus.ThreadMode;
  79. import org.michaelevans.colorart.library.ColorArt;
  80. import org.parceler.Parcels;
  81. import java.io.IOException;
  82. import java.util.ArrayList;
  83. import java.util.List;
  84. import javax.inject.Inject;
  85. import androidx.annotation.NonNull;
  86. import androidx.constraintlayout.widget.ConstraintLayout;
  87. import autodagger.AutoInjector;
  88. import butterknife.BindView;
  89. import butterknife.OnClick;
  90. import io.reactivex.Observer;
  91. import io.reactivex.android.schedulers.AndroidSchedulers;
  92. import io.reactivex.disposables.Disposable;
  93. import io.reactivex.schedulers.Schedulers;
  94. import okhttp3.Cache;
  95. @AutoInjector(NextcloudTalkApplication.class)
  96. public class CallNotificationController extends BaseController {
  97. private static final String TAG = "CallNotificationController";
  98. @Inject
  99. NcApi ncApi;
  100. @Inject
  101. AppPreferences appPreferences;
  102. @Inject
  103. Cache cache;
  104. @Inject
  105. EventBus eventBus;
  106. @BindView(R.id.conversationNameTextView)
  107. TextView conversationNameTextView;
  108. @BindView(R.id.avatarImageView)
  109. ImageView avatarImageView;
  110. @BindView(R.id.callAnswerVoiceOnlyView)
  111. MagicFlipView callAnswerVoiceOnlyView;
  112. @BindView(R.id.callAnswerCameraView)
  113. MagicFlipView callAnswerCameraView;
  114. @BindView(R.id.backgroundImageView)
  115. ImageView backgroundImageView;
  116. @BindView(R.id.incomingTextRelativeLayout)
  117. RelativeLayout incomingTextRelativeLayout;
  118. private List<Disposable> disposablesList = new ArrayList<>();
  119. private Bundle originalBundle;
  120. private String roomId;
  121. private UserEntity userBeingCalled;
  122. private String credentials;
  123. private Conversation currentConversation;
  124. private MediaPlayer mediaPlayer;
  125. private boolean leavingScreen = false;
  126. private RenderScript renderScript;
  127. private Vibrator vibrator;
  128. private Handler handler;
  129. public CallNotificationController(Bundle args) {
  130. super(args);
  131. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  132. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  133. this.currentConversation = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ROOM));
  134. this.userBeingCalled = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  135. this.originalBundle = args;
  136. credentials = ApiUtils.getCredentials(userBeingCalled.getUsername(), userBeingCalled.getToken());
  137. }
  138. @Override
  139. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  140. return inflater.inflate(R.layout.controller_call_notification, container, false);
  141. }
  142. private void showAnswerControls() {
  143. callAnswerCameraView.setVisibility(View.VISIBLE);
  144. callAnswerVoiceOnlyView.setVisibility(View.VISIBLE);
  145. }
  146. @OnClick(R.id.callControlHangupView)
  147. void hangup() {
  148. leavingScreen = true;
  149. if (getActivity() != null) {
  150. getActivity().finish();
  151. }
  152. }
  153. @OnClick(R.id.callAnswerCameraView)
  154. void answerWithCamera() {
  155. originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  156. proceedToCall();
  157. }
  158. @OnClick(R.id.callAnswerVoiceOnlyView)
  159. void answerVoiceOnly() {
  160. originalBundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  161. proceedToCall();
  162. }
  163. private void proceedToCall() {
  164. originalBundle.putString(BundleKeys.KEY_ROOM_TOKEN, currentConversation.getToken());
  165. getRouter().replaceTopController(RouterTransaction.with(new CallController(originalBundle))
  166. .popChangeHandler(new HorizontalChangeHandler())
  167. .pushChangeHandler(new HorizontalChangeHandler()));
  168. }
  169. private void checkIfAnyParticipantsRemainInRoom() {
  170. ncApi.getPeersForCall(credentials, ApiUtils.getUrlForParticipants(userBeingCalled.getBaseUrl(),
  171. currentConversation.getToken()))
  172. .subscribeOn(Schedulers.newThread())
  173. .takeWhile(observable -> !leavingScreen)
  174. .retry(3)
  175. .subscribe(new Observer<ParticipantsOverall>() {
  176. @Override
  177. public void onSubscribe(Disposable d) {
  178. disposablesList.add(d);
  179. }
  180. @Override
  181. public void onNext(ParticipantsOverall participantsOverall) {
  182. boolean hasParticipantsInCall = false;
  183. boolean inCallOnDifferentDevice = false;
  184. List<Participant> participantList = participantsOverall.getOcs().getData();
  185. for (Participant participant : participantList) {
  186. if (participant.getParticipantFlags() != Participant.ParticipantFlags.NOT_IN_CALL) {
  187. hasParticipantsInCall = true;
  188. if (participant.getUserId().equals(userBeingCalled.getUserId())) {
  189. inCallOnDifferentDevice = true;
  190. break;
  191. }
  192. }
  193. }
  194. if (!hasParticipantsInCall || inCallOnDifferentDevice) {
  195. if (getActivity() != null) {
  196. getActivity().runOnUiThread(() -> hangup());
  197. }
  198. }
  199. }
  200. @Override
  201. public void onError(Throwable e) {
  202. }
  203. @Override
  204. public void onComplete() {
  205. if (!leavingScreen) {
  206. checkIfAnyParticipantsRemainInRoom();
  207. }
  208. }
  209. });
  210. }
  211. private void handleFromNotification() {
  212. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(userBeingCalled.getBaseUrl()))
  213. .subscribeOn(Schedulers.newThread())
  214. .retry(3)
  215. .observeOn(AndroidSchedulers.mainThread())
  216. .subscribe(new Observer<RoomsOverall>() {
  217. @Override
  218. public void onSubscribe(Disposable d) {
  219. disposablesList.add(d);
  220. }
  221. @Override
  222. public void onNext(RoomsOverall roomsOverall) {
  223. for (Conversation conversation : roomsOverall.getOcs().getData()) {
  224. if (roomId.equals(conversation.getRoomId())) {
  225. currentConversation = conversation;
  226. runAllThings();
  227. break;
  228. }
  229. }
  230. }
  231. @Override
  232. public void onError(Throwable e) {
  233. }
  234. @Override
  235. public void onComplete() {
  236. }
  237. });
  238. }
  239. private void runAllThings() {
  240. if (conversationNameTextView != null) {
  241. conversationNameTextView.setText(currentConversation.getDisplayName());
  242. }
  243. loadAvatar();
  244. checkIfAnyParticipantsRemainInRoom();
  245. showAnswerControls();
  246. }
  247. @SuppressLint("LongLogTag")
  248. @Override
  249. protected void onViewBound(@NonNull View view) {
  250. super.onViewBound(view);
  251. renderScript = RenderScript.create(getActivity());
  252. if (handler == null) {
  253. handler = new Handler();
  254. try {
  255. cache.evictAll();
  256. } catch (IOException e) {
  257. Log.e(TAG, "Failed to evict cache");
  258. }
  259. }
  260. if (currentConversation == null) {
  261. handleFromNotification();
  262. } else {
  263. runAllThings();
  264. }
  265. if (DoNotDisturbUtils.shouldPlaySound()) {
  266. String callRingtonePreferenceString = appPreferences.getCallRingtoneUri();
  267. Uri ringtoneUri;
  268. if (TextUtils.isEmpty(callRingtonePreferenceString)) {
  269. // play default sound
  270. ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() +
  271. "/raw/librem_by_feandesign_call");
  272. } else {
  273. try {
  274. RingtoneSettings ringtoneSettings = LoganSquare.parse(callRingtonePreferenceString, RingtoneSettings.class);
  275. ringtoneUri = ringtoneSettings.getRingtoneUri();
  276. } catch (IOException e) {
  277. Log.e(TAG, "Failed to parse ringtone settings");
  278. ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() +
  279. "/raw/librem_by_feandesign_call");
  280. }
  281. }
  282. if (ringtoneUri != null && getActivity() != null) {
  283. mediaPlayer = new MediaPlayer();
  284. try {
  285. mediaPlayer.setDataSource(getActivity(), ringtoneUri);
  286. mediaPlayer.setLooping(true);
  287. AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes
  288. .CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build();
  289. mediaPlayer.setAudioAttributes(audioAttributes);
  290. mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
  291. mediaPlayer.prepareAsync();
  292. } catch (IOException e) {
  293. Log.e(TAG, "Failed to set data source");
  294. }
  295. }
  296. }
  297. if (DoNotDisturbUtils.shouldVibrate(appPreferences.getShouldVibrateSetting())) {
  298. vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
  299. if (vibrator != null) {
  300. long[] vibratePattern = new long[]{0, 400, 800, 600, 800, 800, 800, 1000};
  301. int[] amplitudes = new int[]{0, 255, 0, 255, 0, 255, 0, 255};
  302. VibrationEffect vibrationEffect;
  303. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  304. if (vibrator.hasAmplitudeControl()) {
  305. vibrationEffect = VibrationEffect.createWaveform(vibratePattern, amplitudes, -1);
  306. vibrator.vibrate(vibrationEffect);
  307. } else {
  308. vibrationEffect = VibrationEffect.createWaveform(vibratePattern, -1);
  309. vibrator.vibrate(vibrationEffect);
  310. }
  311. } else {
  312. vibrator.vibrate(vibratePattern, -1);
  313. }
  314. }
  315. handler.postDelayed(() -> {
  316. if (vibrator != null) {
  317. vibrator.cancel();
  318. }
  319. }, 10000);
  320. }
  321. }
  322. @Subscribe(threadMode = ThreadMode.MAIN)
  323. public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
  324. ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) avatarImageView.getLayoutParams();
  325. int dimen = (int) getResources().getDimension(R.dimen.avatar_size_very_big);
  326. layoutParams.width = dimen;
  327. layoutParams.height = dimen;
  328. avatarImageView.setLayoutParams(layoutParams);
  329. }
  330. @Override
  331. protected void onDetach(@NonNull View view) {
  332. super.onDetach(view);
  333. eventBus.unregister(this);
  334. }
  335. @Override
  336. protected void onAttach(@NonNull View view) {
  337. super.onAttach(view);
  338. eventBus.register(this);
  339. }
  340. private void loadAvatar() {
  341. int avatarSize = Math.round(NextcloudTalkApplication
  342. .getSharedApplication().getResources().getDimension(R.dimen.avatar_fetching_size_very_big));
  343. switch (currentConversation.getType()) {
  344. case ROOM_TYPE_ONE_TO_ONE_CALL:
  345. avatarImageView.setVisibility(View.VISIBLE);
  346. GlideUrl glideUrl = new GlideUrl(ApiUtils.getUrlForAvatarWithName(userBeingCalled.getBaseUrl(),
  347. currentConversation.getName(), R.dimen.avatar_size_very_big), new LazyHeaders.Builder()
  348. .setHeader("Accept", "image/*")
  349. .setHeader("User-Agent", ApiUtils.getUserAgent())
  350. .build());
  351. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  352. .asBitmap()
  353. .diskCacheStrategy(DiskCacheStrategy.NONE)
  354. .load(glideUrl)
  355. .centerInside()
  356. .override(avatarSize, avatarSize)
  357. .into(new SimpleTarget<Bitmap>() {
  358. @Override
  359. public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
  360. if (getActivity() != null && avatarImageView != null) {
  361. avatarImageView.setImageBitmap(TransformationUtils.circleCrop(GlideApp.get
  362. (getActivity()).getBitmapPool(), resource, avatarSize, avatarSize));
  363. }
  364. if (getResources() != null && incomingTextRelativeLayout != null) {
  365. incomingTextRelativeLayout.setBackground(getResources().getDrawable(R.drawable
  366. .incoming_gradient));
  367. }
  368. if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 200 &&
  369. userBeingCalled.hasSpreedCapabilityWithName("no-ping")) {
  370. final Allocation input = Allocation.createFromBitmap(renderScript, resource);
  371. final Allocation output = Allocation.createTyped(renderScript, input.getType());
  372. final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element
  373. .U8_4(renderScript));
  374. script.setRadius(15f);
  375. script.setInput(input);
  376. script.forEach(output);
  377. output.copyTo(resource);
  378. if (backgroundImageView != null && backgroundImageView != null) {
  379. backgroundImageView.setImageDrawable(new BitmapDrawable(resource));
  380. }
  381. } else if (AvatarStatusCodeHolder.getInstance().getStatusCode() == 201) {
  382. ColorArt colorArt = new ColorArt(resource);
  383. int color = colorArt.getBackgroundColor();
  384. float[] hsv = new float[3];
  385. Color.colorToHSV(color, hsv);
  386. hsv[2] *= 0.75f;
  387. color = Color.HSVToColor(hsv);
  388. if (backgroundImageView != null) {
  389. backgroundImageView.setImageDrawable(new ColorDrawable(color));
  390. }
  391. }
  392. }
  393. });
  394. break;
  395. case ROOM_GROUP_CALL:
  396. if (avatarImageView != null) {
  397. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  398. .asBitmap()
  399. .diskCacheStrategy(DiskCacheStrategy.NONE)
  400. .load(R.drawable.ic_people_group_white_24px)
  401. .centerInside()
  402. .override(avatarSize, avatarSize)
  403. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  404. .into(avatarImageView);
  405. }
  406. case ROOM_PUBLIC_CALL:
  407. if (avatarImageView != null) {
  408. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  409. .asBitmap()
  410. .diskCacheStrategy(DiskCacheStrategy.NONE)
  411. .load(R.drawable.ic_link_white_24px)
  412. .centerInside()
  413. .override(avatarSize, avatarSize)
  414. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  415. .into(avatarImageView);
  416. }
  417. break;
  418. default:
  419. }
  420. }
  421. private void endMediaAndVibratorNotifications() {
  422. if (mediaPlayer != null) {
  423. if (mediaPlayer.isPlaying()) {
  424. mediaPlayer.stop();
  425. }
  426. mediaPlayer.release();
  427. mediaPlayer = null;
  428. }
  429. if (vibrator != null) {
  430. vibrator.cancel();
  431. }
  432. }
  433. @Override
  434. public void onDestroy() {
  435. AvatarStatusCodeHolder.getInstance().setStatusCode(0);
  436. leavingScreen = true;
  437. if (handler != null) {
  438. handler.removeCallbacksAndMessages(null);
  439. handler = null;
  440. }
  441. dispose();
  442. endMediaAndVibratorNotifications();
  443. super.onDestroy();
  444. }
  445. private void dispose() {
  446. Disposable disposable;
  447. for (int i = 0; i < disposablesList.size(); i++) {
  448. if (!(disposable = disposablesList.get(i)).isDisposed()) {
  449. disposable.dispose();
  450. }
  451. }
  452. }
  453. }