/
MessagesFragment.java
1568 lines (1393 loc) · 66.3 KB
/
MessagesFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package co.tinode.tindroid;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.AutomaticGainControl;
import android.media.audiofx.NoiseSuppressor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.core.content.ContextCompat;
import androidx.core.view.ContentInfoCompat;
import androidx.core.view.MenuHost;
import androidx.core.view.MenuProvider;
import androidx.core.view.OnReceiveContentListener;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.work.Data;
import androidx.work.Operation;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;
import co.tinode.tindroid.db.BaseDb;
import co.tinode.tindroid.db.SqlStore;
import co.tinode.tindroid.db.StoredTopic;
import co.tinode.tindroid.format.SendForwardedFormatter;
import co.tinode.tindroid.format.SendReplyFormatter;
import co.tinode.tindroid.media.VxCard;
import co.tinode.tindroid.widgets.MovableActionButton;
import co.tinode.tindroid.widgets.WaveDrawable;
import co.tinode.tinodesdk.ComTopic;
import co.tinode.tinodesdk.PromisedReply;
import co.tinode.tinodesdk.Storage;
import co.tinode.tinodesdk.Tinode;
import co.tinode.tinodesdk.model.AccessChange;
import co.tinode.tinodesdk.model.Acs;
import co.tinode.tinodesdk.model.AcsHelper;
import co.tinode.tinodesdk.model.Drafty;
import co.tinode.tinodesdk.model.MetaSetSub;
import co.tinode.tinodesdk.model.MsgSetMeta;
import co.tinode.tinodesdk.model.PrivateType;
import co.tinode.tinodesdk.model.ServerMessage;
import co.tinode.tinodesdk.model.Subscription;
/**
* Fragment handling message display and message sending.
*/
public class MessagesFragment extends Fragment implements MenuProvider {
private static final String TAG = "MessageFragment";
private static final int MESSAGES_TO_LOAD = 24;
private static final String[] SUPPORTED_MIME_TYPES = new String[]{"image/*"};
static final String MESSAGE_TO_SEND = "messageText";
static final String MESSAGE_TEXT_ACTION = "messageTextAction";
static final String MESSAGE_QUOTED = "quotedDrafty";
static final String MESSAGE_QUOTED_SEQ_ID = "quotedSeqID";
static final int ZONE_CANCEL = 0;
static final int ZONE_LOCK = 1;
// Number of milliseconds between audio samples for recording visualization.
static final int AUDIO_SAMPLING = 100;
// Minimum duration of an audio recording in milliseconds.
static final int MIN_DURATION = 2000;
// Maximum duration of an audio recording in milliseconds.
static final int MAX_DURATION = 600_000;
private ComTopic<VxCard> mTopic;
private LinearLayoutManager mMessageViewLayoutManager;
private RecyclerView mRecyclerView;
private MessagesAdapter mMessagesAdapter;
private SwipeRefreshLayout mRefresher;
private FloatingActionButton mGoToLatest;
private String mTopicName = null;
private String mMessageToSend = null;
private boolean mChatInvitationShown = false;
private UiUtils.MsgAction mTextAction = UiUtils.MsgAction.NONE;
private int mQuotedSeqID = -1;
private Drafty mQuote = null;
private Drafty mContentToForward = null;
private Drafty mForwardSender = null;
private MediaRecorder mAudioRecorder = null;
private File mAudioRecord = null;
// Timestamp when the recording was started.
private long mRecordingStarted = 0;
// Duration of audio recording.
private int mAudioRecordDuration = 0;
private AcousticEchoCanceler mEchoCanceler;
private NoiseSuppressor mNoiseSuppressor;
private AutomaticGainControl mGainControl;
// Playback of audio recording.
private MediaPlayer mAudioPlayer = null;
// Preview or audio amplitudes.
private AudioSampler mAudioSampler = null;
private final Handler mAudioSamplingHandler = new Handler(Looper.getMainLooper());
private int mVisibleSendPanel = R.id.sendMessagePanel;
private PromisedReply.FailureListener<ServerMessage> mFailureListener;
private final ActivityResultLauncher<String> mFileOpenerRequestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
// Check if permission is granted.
if (isGranted) {
openFileSelector(requireActivity(), false);
}
});
private final ActivityResultLauncher<String[]> mImagePickerRequestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
for (Map.Entry<String,Boolean> e : result.entrySet()) {
// Check if all required permissions are granted.
if (!e.getValue()) {
return;
}
}
// Try to open the image selector again.
openMediaSelector(requireActivity(), false);
});
private final ActivityResultLauncher<String[]> mAudioRecorderPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
for (Map.Entry<String,Boolean> e : result.entrySet()) {
if (!e.getValue()) {
// Some permission is missing. Disable audio recording button.
Activity activity = requireActivity();
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
activity.findViewById(R.id.audioRecorder).setEnabled(false);
return;
}
}
});
private final ActivityResultLauncher<String> mFilePickerLauncher =
registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
if (uri == null) {
return;
}
final MessageActivity activity = (MessageActivity) requireActivity();
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
final Bundle args = new Bundle();
args.putParcelable(AttachmentHandler.ARG_LOCAL_URI, uri);
args.putString(AttachmentHandler.ARG_OPERATION, AttachmentHandler.ARG_OPERATION_FILE);
args.putString(Const.INTENT_EXTRA_TOPIC, mTopicName);
// Show attachment preview.
activity.showFragment(MessageActivity.FRAGMENT_FILE_PREVIEW, args, true);
});
private final ActivityResultLauncher<String> mNotificationsPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (!isGranted) {
final MessageActivity activity = (MessageActivity) requireActivity();
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
Toast.makeText(activity, R.string.permission_missing, Toast.LENGTH_LONG).show();
}
});
private final ActivityResultLauncher<Object> mMediaPickerLauncher =
registerForActivityResult(new MediaPickerContract(), uri -> {
if (uri == null) {
return;
}
final MessageActivity activity = (MessageActivity) requireActivity();
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
String mimeType = activity.getContentResolver().getType(uri);
boolean isVideo = mimeType != null && mimeType.startsWith("video");
final Bundle args = new Bundle();
args.putParcelable(AttachmentHandler.ARG_LOCAL_URI, uri);
args.putString(AttachmentHandler.ARG_FILE_NAME, uri.getLastPathSegment());
args.putString(AttachmentHandler.ARG_FILE_PATH, uri.getPath());
args.putString(AttachmentHandler.ARG_OPERATION,
isVideo ? AttachmentHandler.ARG_OPERATION_VIDEO :
AttachmentHandler.ARG_OPERATION_IMAGE);
args.putString(Const.INTENT_EXTRA_TOPIC, mTopicName);
// Show attachment preview.
activity.showFragment(isVideo ? MessageActivity.FRAGMENT_VIEW_VIDEO :
MessageActivity.FRAGMENT_VIEW_IMAGE, args, true);
});
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_messages, container, false);
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstance) {
final MessageActivity activity = (MessageActivity) requireActivity();
((MenuHost) activity).addMenuProvider(this, getViewLifecycleOwner(),
Lifecycle.State.RESUMED);
mGoToLatest = activity.findViewById(R.id.goToLatest);
mGoToLatest.setOnClickListener(v -> scrollToBottom(true));
mMessageViewLayoutManager = new LinearLayoutManager(activity) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
// This is a hack for IndexOutOfBoundsException:
// Inconsistency detected. Invalid view holder adapter positionViewHolder
// It happens when two uploads are started at the same time.
// See discussion here:
// https://stackoverflow.com/questions/31759171/recyclerview-and-java-lang-indexoutofboundsexception-inconsistency-detected-in
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.i(TAG, "meet a IOOBE in RecyclerView", e);
}
}
};
mMessageViewLayoutManager.setReverseLayout(true);
mRecyclerView = view.findViewById(R.id.messages_container);
mRecyclerView.setLayoutManager(mMessageViewLayoutManager);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
if (adapter == null) {
return;
}
int itemCount = adapter.getItemCount();
int pos = mMessageViewLayoutManager.findLastVisibleItemPosition();
if (itemCount - pos < 4) {
((MessagesAdapter) adapter).loadNextPage();
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
int pos = mMessageViewLayoutManager.findFirstVisibleItemPosition();
if (dy > 5 && pos > 2) {
mGoToLatest.show();
} else if (dy < -5 || pos == 0) {
mGoToLatest.hide();
}
}
});
mRefresher = view.findViewById(R.id.swipe_refresher);
mMessagesAdapter = new MessagesAdapter(activity, mRefresher);
mRecyclerView.setAdapter(mMessagesAdapter);
mRefresher.setOnRefreshListener(() -> {
if (!mMessagesAdapter.loadNextPage() && !StoredTopic.isAllDataLoaded(mTopic)) {
try {
mTopic.getMeta(mTopic.getMetaGetBuilder().withEarlierData(MESSAGES_TO_LOAD).build())
.thenApply(
new PromisedReply.SuccessListener<ServerMessage>() {
@Override
public PromisedReply<ServerMessage> onSuccess(ServerMessage result) {
activity.runOnUiThread(() -> mRefresher.setRefreshing(false));
return null;
}
},
new PromisedReply.FailureListener<ServerMessage>() {
@Override
public PromisedReply<ServerMessage> onFailure(Exception err) {
activity.runOnUiThread(() -> mRefresher.setRefreshing(false));
return null;
}
}
);
} catch (Exception e) {
mRefresher.setRefreshing(false);
}
} else {
mRefresher.setRefreshing(false);
}
});
mFailureListener = new UiUtils.ToastFailureListener(activity);
AppCompatImageButton audio = setupAudioForms(activity, view);
AppCompatImageButton send = view.findViewById(R.id.chatSendButton);
send.setOnClickListener(v -> sendText(activity));
view.findViewById(R.id.chatForwardButton).setOnClickListener(v -> sendText(activity));
AppCompatImageButton doneEditing = view.findViewById(R.id.chatEditDoneButton);
doneEditing.setOnClickListener(v -> sendText(activity));
// Send image button
view.findViewById(R.id.attachImage).setOnClickListener(v -> openMediaSelector(activity, true));
// Send file button
view.findViewById(R.id.attachFile).setOnClickListener(v -> openFileSelector(activity, true));
// Cancel reply preview button.
view.findViewById(R.id.cancelPreview).setOnClickListener(v -> cancelPreview(activity));
view.findViewById(R.id.cancelForwardingPreview).setOnClickListener(v -> cancelPreview(activity));
EditText editor = view.findViewById(R.id.editMessage);
ViewCompat.setOnReceiveContentListener(editor, SUPPORTED_MIME_TYPES, new StickerReceiver());
// Send notification on key presses
editor.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (count > 0 || before > 0) {
activity.sendKeyPress();
}
// Show either [send] or [record audio] or [done editing] button.
if (mTextAction == UiUtils.MsgAction.EDIT) {
doneEditing.setVisibility(View.VISIBLE);
audio.setVisibility(View.INVISIBLE);
send.setVisibility(View.INVISIBLE);
} else if (charSequence.length() > 0) {
doneEditing.setVisibility(View.INVISIBLE);
audio.setVisibility(View.INVISIBLE);
send.setVisibility(View.VISIBLE);
} else {
doneEditing.setVisibility(View.INVISIBLE);
audio.setVisibility(View.VISIBLE);
send.setVisibility(View.INVISIBLE);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
view.findViewById(R.id.enablePeerButton).setOnClickListener(view1 -> {
// Enable peer.
Acs am = new Acs(mTopic.getAccessMode());
am.update(new AccessChange(null, "+RW"));
mTopic.setMeta(new MsgSetMeta.Builder<VxCard, PrivateType>()
.with(new MetaSetSub(mTopic.getName(), am.getGiven())).build())
.thenCatch(new UiUtils.ToastFailureListener(activity));
});
// Monitor status of attachment uploads and update messages accordingly.
WorkManager.getInstance(activity).getWorkInfosByTagLiveData(AttachmentHandler.TAG_UPLOAD_WORK)
.observe(activity, workInfos -> {
for (WorkInfo wi : workInfos) {
WorkInfo.State state = wi.getState();
switch (state) {
case RUNNING: {
Data data = wi.getProgress();
String topicName = data.getString(AttachmentHandler.ARG_TOPIC_NAME);
if (topicName == null) {
// Not a progress report, just a status change.
break;
}
if (!topicName.equals(mTopicName)) {
break;
}
long progress = data.getLong(AttachmentHandler.ARG_PROGRESS, -1);
if (progress < 0) {
break;
}
if (progress == 0) {
// New message. Update.
runMessagesLoader(mTopicName);
break;
}
long msgId = data.getLong(AttachmentHandler.ARG_MSG_ID, -1L);
final int position = findItemPositionById(msgId);
if (position >= 0) {
long total = data.getLong(AttachmentHandler.ARG_FILE_SIZE, 1L);
mMessagesAdapter.notifyItemChanged(position, (float) progress / total);
}
break;
}
case SUCCEEDED: {
Data result = wi.getOutputData();
String topicName = result.getString(AttachmentHandler.ARG_TOPIC_NAME);
if (topicName == null) {
break;
}
long msgId = result.getLong(AttachmentHandler.ARG_MSG_ID, -1L);
if (msgId > 0 && topicName.equals(mTopicName)) {
activity.syncMessages(msgId, true);
}
break;
}
case CANCELLED:
// When cancelled wi.getOutputData() returns empty Data.
case ENQUEUED:
case BLOCKED:
// Do nothing.
break;
case FAILED: {
Data failure = wi.getOutputData();
String topicName = failure.getString(AttachmentHandler.ARG_TOPIC_NAME);
if (topicName == null) {
break;
}
if (topicName.equals(mTopicName)) {
long msgId = failure.getLong(AttachmentHandler.ARG_MSG_ID, -1L);
boolean fatal = failure.getBoolean(AttachmentHandler.ARG_FATAL, false);
SqlStore store = BaseDb.getInstance().getStore();
Storage.Message msg = store.getMessageById(msgId);
if (msg != null && BaseDb.isUnsentSeq(msg.getSeqId())) {
if (fatal) {
store.msgDiscard(mTopic, msgId);
}
runMessagesLoader(mTopicName);
String error = failure.getString(AttachmentHandler.ARG_ERROR);
Toast.makeText(activity, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
}
});
}
@Override
@SuppressWarnings("unchecked")
public void onResume() {
super.onResume();
final MessageActivity activity = (MessageActivity) requireActivity();
Bundle args = getArguments();
if (args != null) {
mTopicName = args.getString(Const.INTENT_EXTRA_TOPIC);
}
if (mTopicName != null) {
mTopic = (ComTopic<VxCard>) Cache.getTinode().getTopic(mTopicName);
runMessagesLoader(mTopicName);
} else {
mTopic = null;
}
mRefresher.setRefreshing(false);
updateFormValues();
activity.sendNoteRead(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
NotificationManager nm = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
if (nm != null && !nm.areNotificationsEnabled()) {
mNotificationsPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS);
}
}
}
void runMessagesLoader(String topicName) {
if (mMessagesAdapter != null) {
mMessagesAdapter.resetContent(topicName);
}
}
private void setSendPanelVisible(Activity activity, int id) {
if (mVisibleSendPanel == id) {
return;
}
activity.findViewById(id).setVisibility(View.VISIBLE);
activity.findViewById(mVisibleSendPanel).setVisibility(View.GONE);
mVisibleSendPanel = id;
}
@SuppressLint("ClickableViewAccessibility")
private AppCompatImageButton setupAudioForms(AppCompatActivity activity, View view) {
// Audio recorder button.
MovableActionButton mab = view.findViewById(R.id.audioRecorder);
// Lock button
ImageView lockFab = view.findViewById(R.id.lockAudioRecording);
// Lock button
ImageView deleteFab = view.findViewById(R.id.deleteAudioRecording);
// Play button in locked recording panel.
AppCompatImageButton playButton = view.findViewById(R.id.playRecording);
// Pause button in locked recording panel when playing back.
AppCompatImageButton pauseButton = view.findViewById(R.id.pauseRecording);
// Stop recording button in locked recording panel.
AppCompatImageButton stopButton = view.findViewById(R.id.stopRecording);
// ImageView with waveform visualization.
ImageView wave = view.findViewById(R.id.audioWave);
wave.setBackground(new WaveDrawable(getResources(), 5));
wave.setOnTouchListener((v, event) -> {
if (mAudioRecordDuration > 0 && mAudioPlayer != null && event.getAction() == MotionEvent.ACTION_DOWN) {
float fraction = event.getX() / v.getWidth();
mAudioPlayer.seekTo((int) (fraction * mAudioRecordDuration));
((WaveDrawable) v.getBackground()).seekTo(fraction);
return true;
}
return false;
});
ImageView waveShort = view.findViewById(R.id.audioWaveShort);
waveShort.setBackground(new WaveDrawable(getResources()));
// Recording timer.
TextView timerView = view.findViewById(R.id.duration);
TextView timerShortView = view.findViewById(R.id.durationShort);
// Launch audio recorder.
AppCompatImageButton audio = view.findViewById(R.id.chatAudioButton);
final Runnable visualizer = new Runnable() {
@Override
public void run() {
if (mAudioRecorder != null) {
int x = mAudioRecorder.getMaxAmplitude();
mAudioSampler.put(x);
if (mVisibleSendPanel == R.id.recordAudioPanel) {
((WaveDrawable) wave.getBackground()).put(x);
timerView.setText(UiUtils.millisToTime((int) (SystemClock.uptimeMillis() - mRecordingStarted)));
} else if (mVisibleSendPanel == R.id.recordAudioShortPanel) {
((WaveDrawable) waveShort.getBackground()).put(x);
timerShortView.setText(UiUtils.millisToTime((int) (SystemClock.uptimeMillis() - mRecordingStarted)));
}
mAudioSamplingHandler.postDelayed(this, AUDIO_SAMPLING);
((MessageActivity) activity).sendRecordingProgress(true);
}
}
};
mab.setConstraintChecker((newPos, startPos, buttonRect, parentRect) -> {
// Constrain button moves to strictly vertical UP or horizontal LEFT (no diagonal).
float dX = Math.min(0, newPos.x - startPos.x);
float dY = Math.min(0, newPos.y - startPos.y);
if (Math.abs(dX) > Math.abs(dY)) {
// Horizontal move.
newPos.x = Math.max(parentRect.left, newPos.x);
newPos.y = startPos.y;
} else {
// Vertical move.
newPos.x = startPos.x;
newPos.y = Math.max(parentRect.top, newPos.y);
}
return newPos;
});
mab.setOnActionListener(new MovableActionButton.ActionListener() {
@Override
public boolean onUp(float x, float y) {
if (mAudioRecorder != null) {
releaseAudio(true);
sendAudio(activity);
}
mab.setVisibility(View.INVISIBLE);
lockFab.setVisibility(View.GONE);
deleteFab.setVisibility(View.GONE);
audio.setVisibility(View.VISIBLE);
setSendPanelVisible(activity, R.id.sendMessagePanel);
return true;
}
@Override
public boolean onZoneReached(int id) {
mab.performHapticFeedback(android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.Q ?
(id == ZONE_CANCEL ? HapticFeedbackConstants.REJECT : HapticFeedbackConstants.CONFIRM) :
HapticFeedbackConstants.CONTEXT_CLICK
);
mab.setVisibility(View.INVISIBLE);
lockFab.setVisibility(View.GONE);
deleteFab.setVisibility(View.GONE);
audio.setVisibility(View.VISIBLE);
if (id == ZONE_CANCEL) {
if (mAudioRecorder != null) {
releaseAudio(false);
}
setSendPanelVisible(activity, R.id.sendMessagePanel);
releaseAudio(false);
} else {
playButton.setVisibility(View.GONE);
stopButton.setVisibility(View.VISIBLE);
setSendPanelVisible(activity, R.id.recordAudioPanel);
}
return true;
}
});
GestureDetector gd = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(@NonNull MotionEvent e) {
if (!UiUtils.isPermissionGranted(activity, Manifest.permission.RECORD_AUDIO)) {
mAudioRecorderPermissionLauncher.launch(new String[] {
Manifest.permission.RECORD_AUDIO, Manifest.permission.MODIFY_AUDIO_SETTINGS
});
return;
}
if (mAudioRecorder == null) {
initAudioRecorder(activity);
}
try {
mAudioRecorder.start();
mRecordingStarted = SystemClock.uptimeMillis();
visualizer.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Failed to start audio recording", ex);
Toast.makeText(activity, R.string.audio_recording_failed, Toast.LENGTH_SHORT).show();
return;
}
mab.setVisibility(View.VISIBLE);
lockFab.setVisibility(View.VISIBLE);
deleteFab.setVisibility(View.VISIBLE);
audio.setVisibility(View.INVISIBLE);
mab.requestFocus();
setSendPanelVisible(activity, R.id.recordAudioShortPanel);
// Cancel zone on the left.
int x = mab.getLeft();
int y = mab.getTop();
int width = mab.getWidth();
int height = mab.getHeight();
mab.addActionZone(ZONE_CANCEL, new Rect(x - (int) (width * 1.5), y,
x - (int) (width * 0.5), y + height));
// Lock zone above.
mab.addActionZone(ZONE_LOCK, new Rect(x, y - (int) (height * 1.5),
x + width, y - (int) (height * 0.5)));
MotionEvent motionEvent = MotionEvent.obtain(
e.getDownTime(), e.getEventTime(),
MotionEvent.ACTION_DOWN,
e.getRawX(),
e.getRawY(),
0
);
mab.dispatchTouchEvent(motionEvent);
}
});
// Ignore the warning: click detection is not needed here.
audio.setOnTouchListener((v, event) -> {
int action = event.getAction();
if (mab.getVisibility() == View.VISIBLE) {
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
audio.setPressed(false);
}
return mab.dispatchTouchEvent(event);
}
return gd.onTouchEvent(event);
});
view.findViewById(R.id.deleteRecording).setOnClickListener(v -> {
WaveDrawable wd = (WaveDrawable) wave.getBackground();
wd.release();
releaseAudio(false);
setSendPanelVisible(activity, R.id.sendMessagePanel);
});
playButton.setOnClickListener(v -> {
pauseButton.setVisibility(View.VISIBLE);
playButton.setVisibility(View.GONE);
WaveDrawable wd = (WaveDrawable) wave.getBackground();
wd.start();
initAudioPlayer(wd, playButton, pauseButton);
mAudioPlayer.start();
});
pauseButton.setOnClickListener(v -> {
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.GONE);
WaveDrawable wd = (WaveDrawable) wave.getBackground();
wd.stop();
mAudioPlayer.pause();
});
stopButton.setOnClickListener(v -> {
playButton.setVisibility(View.VISIBLE);
v.setVisibility(View.GONE);
releaseAudio(true);
WaveDrawable wd = (WaveDrawable) wave.getBackground();
wd.reset();
wd.setDuration(mAudioRecordDuration);
wd.put(mAudioSampler.obtain(96));
wd.seekTo(0f);
});
view.findViewById(R.id.chatSendAudio).setOnClickListener(v -> {
releaseAudio(true);
sendAudio(activity);
setSendPanelVisible(activity, R.id.sendMessagePanel);
});
return audio;
}
private void updateFormValues() {
if (!isAdded()) {
return;
}
final MessageActivity activity = (MessageActivity) requireActivity();
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
if (mTopic == null) {
// Default view when the topic is not available.
activity.findViewById(R.id.notReadable).setVisibility(View.VISIBLE);
activity.findViewById(R.id.notReadableNote).setVisibility(View.VISIBLE);
setSendPanelVisible(activity, R.id.sendMessageDisabled);
UiUtils.setupToolbar(activity, null, mTopicName, false, null, false);
return;
}
UiUtils.setupToolbar(activity, mTopic.getPub(), mTopicName,
mTopic.getOnline(), mTopic.getLastSeen(), mTopic.isDeleted());
Acs acs = mTopic.getAccessMode();
if (acs == null || !acs.isModeDefined()) {
return;
}
activity.findViewById(R.id.replyPreviewWrapper).setVisibility(View.GONE);
if (mTopic.isReader()) {
activity.findViewById(R.id.notReadable).setVisibility(View.GONE);
} else {
activity.findViewById(R.id.notReadable).setVisibility(View.VISIBLE);
activity.findViewById(R.id.notReadableNote).setVisibility(
acs.isReader(Acs.Side.GIVEN) ? View.GONE : View.VISIBLE);
}
if (!mTopic.isWriter() || mTopic.isBlocked() || mTopic.isDeleted()) {
setSendPanelVisible(activity, R.id.sendMessageDisabled);
} else if (mContentToForward != null) {
showContentToForward(activity, mForwardSender, mContentToForward);
} else {
Subscription peer = mTopic.getPeer();
boolean isJoiner = peer != null && peer.acs != null && peer.acs.isJoiner(Acs.Side.WANT);
AcsHelper missing = peer != null && peer.acs != null ? peer.acs.getMissing() : new AcsHelper();
if (isJoiner && (missing.isReader() || missing.isWriter())) {
setSendPanelVisible(activity, R.id.peersMessagingDisabled);
} else {
if (!TextUtils.isEmpty(mMessageToSend)) {
EditText input = activity.findViewById(R.id.editMessage);
if (input.getText().length() == 0) {
input.append(mMessageToSend);
}
mMessageToSend = null;
}
setSendPanelVisible(activity, R.id.sendMessagePanel);
}
}
if (acs.isJoiner(Acs.Side.GIVEN) && acs.getExcessive().toString().contains("RW")) {
showChatInvitationDialog();
}
}
private void scrollToBottom(boolean smooth) {
if (smooth) {
mRecyclerView.smoothScrollToPosition(0);
} else {
mRecyclerView.scrollToPosition(0);
}
}
@Override
public void onPause() {
super.onPause();
releaseAudio(false);
final MessageActivity activity = (MessageActivity) requireActivity();
AudioManager audioManager = (AudioManager) activity.getSystemService(Activity.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(false);
Bundle args = getArguments();
if (args != null) {
args.putString(Const.INTENT_EXTRA_TOPIC, mTopicName);
// Save the text in the send field.
String draft = ((EditText) activity.findViewById(R.id.editMessage)).getText().toString().trim();
args.putString(MESSAGE_TO_SEND, draft);
args.putString(MESSAGE_TEXT_ACTION, mTextAction.name());
args.putInt(MESSAGE_QUOTED_SEQ_ID, mQuotedSeqID);
args.putSerializable(MESSAGE_QUOTED, mQuote);
args.putSerializable(ForwardToFragment.CONTENT_TO_FORWARD, mContentToForward);
args.putSerializable(ForwardToFragment.FORWARDING_FROM_USER, mForwardSender);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Close cursor and release MediaPlayer.
if (mMessagesAdapter != null) {
mMessagesAdapter.releaseAudio();
mMessagesAdapter.resetContent(null);
}
}
@Override
public void onPrepareMenu(@NonNull Menu menu) {
MenuProvider.super.onPrepareMenu(menu);
if (mTopic != null) {
if (mTopic.isDeleted()) {
final Activity activity = requireActivity();
menu.clear();
activity.getMenuInflater().inflate(R.menu.menu_topic_deleted, menu);
} else {
menu.findItem(R.id.action_unmute).setVisible(mTopic.isMuted());
menu.findItem(R.id.action_mute).setVisible(!mTopic.isMuted());
menu.findItem(R.id.action_delete).setVisible(mTopic.isOwner());
menu.findItem(R.id.action_leave).setVisible(!mTopic.isOwner());
menu.findItem(R.id.action_archive).setVisible(!mTopic.isArchived());
menu.findItem(R.id.action_unarchive).setVisible(mTopic.isArchived());
boolean callsEnabled = mTopic.isP2PType() &&
Cache.getTinode().getServerParam("iceServers") != null;
menu.findItem(R.id.action_video_call).setVisible(callsEnabled);
menu.findItem(R.id.action_audio_call).setVisible(callsEnabled);
}
}
}
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_topic, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
final Activity activity = requireActivity();
int id = item.getItemId();
if (id == R.id.action_clear) {
mTopic.delMessages(false).thenApply(new PromisedReply.SuccessListener<ServerMessage>() {
@Override
public PromisedReply<ServerMessage> onSuccess(ServerMessage result) {
runMessagesLoader(mTopicName);
return null;
}
}, mFailureListener);
return true;
} else if (id == R.id.action_unmute || id == R.id.action_mute) {
mTopic.updateMuted(!mTopic.isMuted());
activity.invalidateOptionsMenu();
return true;
} else if (id == R.id.action_leave || id == R.id.action_delete) {
if (mTopic.isDeleted()) {
mTopic.delete(true);
Intent intent = new Intent(activity, ChatsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
activity.finish();
} else {
showDeleteTopicConfirmationDialog(activity, id == R.id.action_delete);
}
return true;
} else if (id == R.id.action_offline) {
Cache.getTinode().reconnectNow(true, false, false);
return true;
}
return false;
}
void setRefreshing(boolean active) {
if (!isAdded()) {
return;
}
mRefresher.setRefreshing(active);
}
private void initAudioRecorder(Activity activity) {
if (mAudioRecord != null) {
mAudioRecord.delete();
mAudioRecord = null;
}
mAudioRecorder = new MediaRecorder();
mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mAudioRecorder.setMaxDuration(MAX_DURATION); // 10 minutes.
mAudioRecorder.setAudioEncodingBitRate(24_000);
mAudioRecorder.setAudioSamplingRate(16_000);
mAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
if (AcousticEchoCanceler.isAvailable()) {
mEchoCanceler = AcousticEchoCanceler.create(MediaRecorder.AudioSource.MIC);
}
if (NoiseSuppressor.isAvailable()) {
mNoiseSuppressor = NoiseSuppressor.create(MediaRecorder.AudioSource.MIC);
}
if (AutomaticGainControl.isAvailable()) {
mGainControl = AutomaticGainControl.create(MediaRecorder.AudioSource.MIC);
}
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try {
mAudioRecord = File.createTempFile("audio", ".m4a", activity.getCacheDir());
mAudioRecorder.setOutputFile(mAudioRecord.getAbsolutePath());
mAudioRecorder.prepare();
mAudioSampler = new AudioSampler();
} catch (IOException ex) {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.w(TAG, "Failed to initialize audio recording", ex);
Toast.makeText(activity, R.string.audio_recording_failed, Toast.LENGTH_SHORT).show();
mAudioRecorder.release();
mAudioRecorder = null;
mAudioSampler = null;
}
}
private synchronized void initAudioPlayer(WaveDrawable waveDrawable, View play, View pause) {
if (mAudioPlayer != null) {
return;
}
final MessageActivity activity = (MessageActivity) requireActivity();
AudioManager audioManager = (AudioManager) activity.getSystemService(Activity.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
mAudioPlayer = new MediaPlayer();
mAudioPlayer.setOnCompletionListener(mp -> {
waveDrawable.reset();
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
});
mAudioPlayer.setAudioAttributes(
new AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_VOICE_CALL).build());
try {
mAudioPlayer.setDataSource(mAudioRecord.getAbsolutePath());
mAudioPlayer.prepare();
if (AutomaticGainControl.isAvailable()) {
AutomaticGainControl agc = AutomaticGainControl.create(mAudioPlayer.getAudioSessionId());
if (agc != null) {
// Even when isAvailable returns true, create() may still return null.
agc.setEnabled(true);