1package eu.siacs.conversations.ui.adapter;
2
3import android.Manifest;
4import android.app.Activity;
5import android.content.Intent;
6import android.content.pm.PackageManager;
7import android.content.res.ColorStateList;
8import android.graphics.Typeface;
9import android.os.Build;
10import android.text.Spannable;
11import android.text.SpannableString;
12import android.text.SpannableStringBuilder;
13import android.text.format.DateUtils;
14import android.text.style.ForegroundColorSpan;
15import android.text.style.RelativeSizeSpan;
16import android.text.style.StyleSpan;
17import android.util.DisplayMetrics;
18import android.view.View;
19import android.view.ViewGroup;
20import android.view.WindowManager;
21import android.widget.ArrayAdapter;
22import android.widget.ImageView;
23import android.widget.LinearLayout;
24import android.widget.RelativeLayout;
25import android.widget.TextView;
26import android.widget.Toast;
27
28import androidx.annotation.AttrRes;
29import androidx.annotation.ColorInt;
30import androidx.annotation.DrawableRes;
31import androidx.annotation.NonNull;
32import androidx.core.app.ActivityCompat;
33import androidx.core.content.ContextCompat;
34import androidx.core.widget.ImageViewCompat;
35
36import com.google.android.material.button.MaterialButton;
37import com.google.android.material.color.MaterialColors;
38import com.google.common.base.Strings;
39
40import java.net.URI;
41import java.util.List;
42import java.util.Locale;
43import java.util.regex.Matcher;
44import java.util.regex.Pattern;
45
46import eu.siacs.conversations.AppSettings;
47import eu.siacs.conversations.Config;
48import eu.siacs.conversations.R;
49import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
50import eu.siacs.conversations.entities.Account;
51import eu.siacs.conversations.entities.Conversation;
52import eu.siacs.conversations.entities.Conversational;
53import eu.siacs.conversations.entities.DownloadableFile;
54import eu.siacs.conversations.entities.Message;
55import eu.siacs.conversations.entities.Message.FileParams;
56import eu.siacs.conversations.entities.RtpSessionStatus;
57import eu.siacs.conversations.entities.Transferable;
58import eu.siacs.conversations.persistance.FileBackend;
59import eu.siacs.conversations.services.MessageArchiveService;
60import eu.siacs.conversations.services.NotificationService;
61import eu.siacs.conversations.ui.ConversationFragment;
62import eu.siacs.conversations.ui.ConversationsActivity;
63import eu.siacs.conversations.ui.XmppActivity;
64import eu.siacs.conversations.ui.service.AudioPlayer;
65import eu.siacs.conversations.ui.text.DividerSpan;
66import eu.siacs.conversations.ui.text.QuoteSpan;
67import eu.siacs.conversations.ui.util.Attachment;
68import eu.siacs.conversations.ui.util.AvatarWorkerTask;
69import eu.siacs.conversations.ui.util.MyLinkify;
70import eu.siacs.conversations.ui.util.QuoteHelper;
71import eu.siacs.conversations.ui.util.ViewUtil;
72import eu.siacs.conversations.ui.widget.ClickableMovementMethod;
73import eu.siacs.conversations.utils.CryptoHelper;
74import eu.siacs.conversations.utils.Emoticons;
75import eu.siacs.conversations.utils.GeoHelper;
76import eu.siacs.conversations.utils.MessageUtils;
77import eu.siacs.conversations.utils.StylingHelper;
78import eu.siacs.conversations.utils.TimeFrameUtils;
79import eu.siacs.conversations.utils.UIHelper;
80import eu.siacs.conversations.xmpp.Jid;
81import eu.siacs.conversations.xmpp.mam.MamReference;
82
83public class MessageAdapter extends ArrayAdapter<Message> {
84
85 public static final String DATE_SEPARATOR_BODY = "DATE_SEPARATOR";
86 private static final int SENT = 0;
87 private static final int RECEIVED = 1;
88 private static final int STATUS = 2;
89 private static final int DATE_SEPARATOR = 3;
90 private static final int RTP_SESSION = 4;
91 private final XmppActivity activity;
92 private final AudioPlayer audioPlayer;
93 private List<String> highlightedTerm = null;
94 private final DisplayMetrics metrics;
95 private OnContactPictureClicked mOnContactPictureClickedListener;
96 private OnContactPictureLongClicked mOnContactPictureLongClickedListener;
97 private boolean colorfulChatBubbles = false;
98 private final boolean mForceNames;
99
100 public MessageAdapter(final XmppActivity activity, final List<Message> messages, final boolean forceNames) {
101 super(activity, 0, messages);
102 this.audioPlayer = new AudioPlayer(this);
103 this.activity = activity;
104 metrics = getContext().getResources().getDisplayMetrics();
105 updatePreferences();
106 this.mForceNames = forceNames;
107 }
108
109 public MessageAdapter(final XmppActivity activity, final List<Message> messages) {
110 this(activity, messages, false);
111 }
112
113 private static void resetClickListener(View... views) {
114 for (View view : views) {
115 view.setOnClickListener(null);
116 }
117 }
118
119 public void flagScreenOn() {
120 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
121 }
122
123 public void flagScreenOff() {
124 activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
125 }
126
127 public void setVolumeControl(final int stream) {
128 activity.setVolumeControlStream(stream);
129 }
130
131 public void setOnContactPictureClicked(OnContactPictureClicked listener) {
132 this.mOnContactPictureClickedListener = listener;
133 }
134
135 public Activity getActivity() {
136 return activity;
137 }
138
139 public void setOnContactPictureLongClicked(
140 OnContactPictureLongClicked listener) {
141 this.mOnContactPictureLongClickedListener = listener;
142 }
143
144 @Override
145 public int getViewTypeCount() {
146 return 5;
147 }
148
149 private int getItemViewType(Message message) {
150 if (message.getType() == Message.TYPE_STATUS) {
151 if (DATE_SEPARATOR_BODY.equals(message.getBody())) {
152 return DATE_SEPARATOR;
153 } else {
154 return STATUS;
155 }
156 } else if (message.getType() == Message.TYPE_RTP_SESSION) {
157 return RTP_SESSION;
158 } else if (message.getStatus() <= Message.STATUS_RECEIVED) {
159 return RECEIVED;
160 } else {
161 return SENT;
162 }
163 }
164
165 @Override
166 public int getItemViewType(int position) {
167 return this.getItemViewType(getItem(position));
168 }
169
170 private void displayStatus(ViewHolder viewHolder, Message message, int type, final BubbleColor bubbleColor) {
171 String filesize = null;
172 String info = null;
173 boolean error = false;
174 if (viewHolder.indicatorReceived != null) {
175 viewHolder.indicatorReceived.setVisibility(View.GONE);
176 }
177
178 if (viewHolder.edit_indicator != null) {
179 if (message.edited()) {
180 viewHolder.edit_indicator.setVisibility(View.VISIBLE);
181 setImageTint(viewHolder.edit_indicator, bubbleColor);
182 } else {
183 viewHolder.edit_indicator.setVisibility(View.GONE);
184 }
185 }
186 final Transferable transferable = message.getTransferable();
187 boolean multiReceived = message.getConversation().getMode() == Conversation.MODE_MULTI
188 && message.getMergedStatus() <= Message.STATUS_RECEIVED;
189 if (message.isFileOrImage() || transferable != null || MessageUtils.unInitiatedButKnownSize(message)) {
190 FileParams params = message.getFileParams();
191 filesize = params.size != null ? UIHelper.filesizeToString(params.size) : null;
192 if (transferable != null && (transferable.getStatus() == Transferable.STATUS_FAILED || transferable.getStatus() == Transferable.STATUS_CANCELLED)) {
193 error = true;
194 }
195 }
196 switch (message.getMergedStatus()) {
197 case Message.STATUS_WAITING:
198 info = getContext().getString(R.string.waiting);
199 break;
200 case Message.STATUS_UNSEND:
201 if (transferable != null) {
202 info = getContext().getString(R.string.sending_file, transferable.getProgress());
203 } else {
204 info = getContext().getString(R.string.sending);
205 }
206 break;
207 case Message.STATUS_OFFERED:
208 info = getContext().getString(R.string.offering);
209 break;
210 case Message.STATUS_SEND_RECEIVED:
211 case Message.STATUS_SEND_DISPLAYED:
212 setImageTint(viewHolder.indicatorReceived, bubbleColor);
213 viewHolder.indicatorReceived.setVisibility(View.VISIBLE);
214 break;
215 case Message.STATUS_SEND_FAILED:
216 final String errorMessage = message.getErrorMessage();
217 if (Message.ERROR_MESSAGE_CANCELLED.equals(errorMessage)) {
218 info = getContext().getString(R.string.cancelled);
219 } else if (errorMessage != null) {
220 final String[] errorParts = errorMessage.split("\\u001f", 2);
221 if (errorParts.length == 2) {
222 switch (errorParts[0]) {
223 case "file-too-large":
224 info = getContext().getString(R.string.file_too_large);
225 break;
226 default:
227 info = getContext().getString(R.string.send_failed);
228 break;
229 }
230 } else {
231 info = getContext().getString(R.string.send_failed);
232 }
233 } else {
234 info = getContext().getString(R.string.send_failed);
235 }
236 error = true;
237 break;
238 default:
239 if (mForceNames || multiReceived) {
240 info = UIHelper.getMessageDisplayName(message);
241 }
242 break;
243 }
244 if (error && type == SENT) {
245 viewHolder.time.setTextColor(MaterialColors.getColor(viewHolder.time, com.google.android.material.R.attr.colorError));
246 } else {
247 setTextColor(viewHolder.time,bubbleColor);
248 }
249 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
250 viewHolder.indicator.setVisibility(View.GONE);
251 } else {
252 boolean verified = false;
253 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
254 final FingerprintStatus status = message.getConversation()
255 .getAccount().getAxolotlService().getFingerprintTrust(
256 message.getFingerprint());
257 if (status != null && status.isVerified()) {
258 verified = true;
259 }
260 }
261 if (verified) {
262 viewHolder.indicator.setImageResource(R.drawable.ic_verified_user_24dp);
263 } else {
264 viewHolder.indicator.setImageResource(R.drawable.ic_lock_24dp);
265 }
266 setImageTint(viewHolder.indicator, bubbleColor);
267 viewHolder.indicator.setVisibility(View.VISIBLE);
268 }
269
270 final String formattedTime = UIHelper.readableTimeDifferenceFull(getContext(), message.getMergedTimeSent());
271 final String bodyLanguage = message.getBodyLanguage();
272 final String bodyLanguageInfo = bodyLanguage == null ? "" : String.format(" \u00B7 %s", bodyLanguage.toUpperCase(Locale.US));
273 if (message.getStatus() <= Message.STATUS_RECEIVED) {
274 if ((filesize != null) && (info != null)) {
275 viewHolder.time.setText(formattedTime + " \u00B7 " + filesize + " \u00B7 " + info + bodyLanguageInfo);
276 } else if ((filesize == null) && (info != null)) {
277 viewHolder.time.setText(formattedTime + " \u00B7 " + info + bodyLanguageInfo);
278 } else if ((filesize != null) && (info == null)) {
279 viewHolder.time.setText(formattedTime + " \u00B7 " + filesize + bodyLanguageInfo);
280 } else {
281 viewHolder.time.setText(formattedTime + bodyLanguageInfo);
282 }
283 } else {
284 if ((filesize != null) && (info != null)) {
285 viewHolder.time.setText(filesize + " \u00B7 " + info + bodyLanguageInfo);
286 } else if ((filesize == null) && (info != null)) {
287 if (error) {
288 viewHolder.time.setText(info + " \u00B7 " + formattedTime + bodyLanguageInfo);
289 } else {
290 viewHolder.time.setText(info);
291 }
292 } else if ((filesize != null) && (info == null)) {
293 viewHolder.time.setText(filesize + " \u00B7 " + formattedTime + bodyLanguageInfo);
294 } else {
295 viewHolder.time.setText(formattedTime + bodyLanguageInfo);
296 }
297 }
298 }
299
300 private void displayInfoMessage(ViewHolder viewHolder, CharSequence text, final BubbleColor bubbleColor) {
301 viewHolder.download_button.setVisibility(View.GONE);
302 viewHolder.audioPlayer.setVisibility(View.GONE);
303 viewHolder.image.setVisibility(View.GONE);
304 viewHolder.messageBody.setVisibility(View.VISIBLE);
305 viewHolder.messageBody.setText(text);
306 viewHolder.messageBody.setTextColor(bubbleToOnSurfaceVariant(viewHolder.messageBody,bubbleColor));
307 viewHolder.messageBody.setTextIsSelectable(false);
308 }
309
310 private void displayEmojiMessage(final ViewHolder viewHolder, final String body, final BubbleColor bubbleColor) {
311 viewHolder.download_button.setVisibility(View.GONE);
312 viewHolder.audioPlayer.setVisibility(View.GONE);
313 viewHolder.image.setVisibility(View.GONE);
314 viewHolder.messageBody.setVisibility(View.VISIBLE);
315 setTextColor(viewHolder.messageBody, bubbleColor);
316 final Spannable span = new SpannableString(body);
317 float size = Emoticons.isEmoji(body) ? 3.0f : 2.0f;
318 span.setSpan(new RelativeSizeSpan(size), 0, body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
319 viewHolder.messageBody.setText(span);
320 }
321
322 private void applyQuoteSpan(final TextView textView, SpannableStringBuilder body, int start, int end, final BubbleColor bubbleColor) {
323 if (start > 1 && !"\n\n".equals(body.subSequence(start - 2, start).toString())) {
324 body.insert(start++, "\n");
325 body.setSpan(new DividerSpan(false), start - 2, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
326 end++;
327 }
328 if (end < body.length() - 1 && !"\n\n".equals(body.subSequence(end, end + 2).toString())) {
329 body.insert(end, "\n");
330 body.setSpan(new DividerSpan(false), end, end + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
331 }
332 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
333 body.setSpan(new QuoteSpan(bubbleToOnSurfaceVariant(textView, bubbleColor), metrics), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
334 }
335
336 /**
337 * Applies QuoteSpan to group of lines which starts with > or » characters.
338 * Appends likebreaks and applies DividerSpan to them to show a padding between quote and text.
339 */
340 private boolean handleTextQuotes(final TextView textView, final SpannableStringBuilder body, final BubbleColor bubbleColor) {
341 boolean startsWithQuote = false;
342 int quoteDepth = 1;
343 while (QuoteHelper.bodyContainsQuoteStart(body) && quoteDepth <= Config.QUOTE_MAX_DEPTH) {
344 char previous = '\n';
345 int lineStart = -1;
346 int lineTextStart = -1;
347 int quoteStart = -1;
348 for (int i = 0; i <= body.length(); i++) {
349 char current = body.length() > i ? body.charAt(i) : '\n';
350 if (lineStart == -1) {
351 if (previous == '\n') {
352 if (i < body.length() && QuoteHelper.isPositionQuoteStart(body, i)) {
353 // Line start with quote
354 lineStart = i;
355 if (quoteStart == -1) quoteStart = i;
356 if (i == 0) startsWithQuote = true;
357 } else if (quoteStart >= 0) {
358 // Line start without quote, apply spans there
359 applyQuoteSpan(textView, body, quoteStart, i - 1, bubbleColor);
360 quoteStart = -1;
361 }
362 }
363 } else {
364 // Remove extra spaces between > and first character in the line
365 // > character will be removed too
366 if (current != ' ' && lineTextStart == -1) {
367 lineTextStart = i;
368 }
369 if (current == '\n') {
370 body.delete(lineStart, lineTextStart);
371 i -= lineTextStart - lineStart;
372 if (i == lineStart) {
373 // Avoid empty lines because span over empty line can be hidden
374 body.insert(i++, " ");
375 }
376 lineStart = -1;
377 lineTextStart = -1;
378 }
379 }
380 previous = current;
381 }
382 if (quoteStart >= 0) {
383 // Apply spans to finishing open quote
384 applyQuoteSpan(textView, body, quoteStart, body.length(), bubbleColor);
385 }
386 quoteDepth++;
387 }
388 return startsWithQuote;
389 }
390
391 private void displayTextMessage(final ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor, int type) {
392 viewHolder.download_button.setVisibility(View.GONE);
393 viewHolder.image.setVisibility(View.GONE);
394 viewHolder.audioPlayer.setVisibility(View.GONE);
395 viewHolder.messageBody.setVisibility(View.VISIBLE);
396 setTextColor(viewHolder.messageBody, bubbleColor);
397 viewHolder.messageBody.setTypeface(null, Typeface.NORMAL);
398
399 if (message.getBody() != null) {
400 final String nick = UIHelper.getMessageDisplayName(message);
401 SpannableStringBuilder body = message.getMergedBody();
402 boolean hasMeCommand = message.hasMeCommand();
403 if (hasMeCommand) {
404 body = body.replace(0, Message.ME_COMMAND.length(), nick + " ");
405 }
406 if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
407 body = new SpannableStringBuilder(body, 0, Config.MAX_DISPLAY_MESSAGE_CHARS);
408 body.append("\u2026");
409 }
410 Message.MergeSeparator[] mergeSeparators = body.getSpans(0, body.length(), Message.MergeSeparator.class);
411 for (Message.MergeSeparator mergeSeparator : mergeSeparators) {
412 int start = body.getSpanStart(mergeSeparator);
413 int end = body.getSpanEnd(mergeSeparator);
414 body.setSpan(new DividerSpan(true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
415 }
416 boolean startsWithQuote = handleTextQuotes(viewHolder.messageBody, body, bubbleColor);
417 if (!message.isPrivateMessage()) {
418 if (hasMeCommand) {
419 body.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, nick.length(),
420 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
421 }
422 } else {
423 String privateMarker;
424 if (message.getStatus() <= Message.STATUS_RECEIVED) {
425 privateMarker = activity.getString(R.string.private_message);
426 } else {
427 Jid cp = message.getCounterpart();
428 privateMarker = activity.getString(R.string.private_message_to, Strings.nullToEmpty(cp == null ? null : cp.getResource()));
429 }
430 body.insert(0, privateMarker);
431 int privateMarkerIndex = privateMarker.length();
432 if (startsWithQuote) {
433 body.insert(privateMarkerIndex, "\n\n");
434 body.setSpan(new DividerSpan(false), privateMarkerIndex, privateMarkerIndex + 2,
435 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
436 } else {
437 body.insert(privateMarkerIndex, " ");
438 }
439 body.setSpan(new ForegroundColorSpan(bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)), 0, privateMarkerIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
440 body.setSpan(new StyleSpan(Typeface.BOLD), 0, privateMarkerIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
441 if (hasMeCommand) {
442 body.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), privateMarkerIndex + 1,
443 privateMarkerIndex + 1 + nick.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
444 }
445 }
446 if (message.getConversation().getMode() == Conversation.MODE_MULTI && message.getStatus() == Message.STATUS_RECEIVED) {
447 if (message.getConversation() instanceof Conversation conversation) {
448 Pattern pattern = NotificationService.generateNickHighlightPattern(conversation.getMucOptions().getActualNick());
449 Matcher matcher = pattern.matcher(body);
450 while (matcher.find()) {
451 body.setSpan(new StyleSpan(Typeface.BOLD), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
452 }
453 }
454 }
455 Matcher matcher = Emoticons.getEmojiPattern(body).matcher(body);
456 while (matcher.find()) {
457 if (matcher.start() < matcher.end()) {
458 body.setSpan(new RelativeSizeSpan(1.2f), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
459 }
460 }
461
462 StylingHelper.format(body, viewHolder.messageBody.getCurrentTextColor());
463 if (highlightedTerm != null) {
464 StylingHelper.highlight(viewHolder.messageBody, body, highlightedTerm);
465 }
466 MyLinkify.addLinks(body, true);
467 viewHolder.messageBody.setAutoLinkMask(0);
468 viewHolder.messageBody.setText(body);
469 viewHolder.messageBody.setMovementMethod(ClickableMovementMethod.getInstance());
470 } else {
471 viewHolder.messageBody.setText("");
472 viewHolder.messageBody.setTextIsSelectable(false);
473 }
474 }
475
476 private void displayDownloadableMessage(ViewHolder viewHolder, final Message message, String text, final BubbleColor bubbleColor) {
477 toggleWhisperInfo(viewHolder, message, bubbleColor);
478 viewHolder.image.setVisibility(View.GONE);
479 viewHolder.audioPlayer.setVisibility(View.GONE);
480 viewHolder.download_button.setVisibility(View.VISIBLE);
481 viewHolder.download_button.setText(text);
482 final var attachment = Attachment.of(message);
483 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
484 viewHolder.download_button.setIconResource(imageResource);
485 viewHolder.download_button.setOnClickListener(v -> ConversationFragment.downloadFile(activity, message));
486 }
487
488 private void displayOpenableMessage(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
489 toggleWhisperInfo(viewHolder, message, bubbleColor);
490 viewHolder.image.setVisibility(View.GONE);
491 viewHolder.audioPlayer.setVisibility(View.GONE);
492 viewHolder.download_button.setVisibility(View.VISIBLE);
493 viewHolder.download_button.setText(activity.getString(R.string.open_x_file, UIHelper.getFileDescriptionString(activity, message)));
494 final var attachment = Attachment.of(message);
495 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
496 viewHolder.download_button.setIconResource(imageResource);
497 viewHolder.download_button.setOnClickListener(v -> openDownloadable(message));
498 }
499
500 private void displayLocationMessage(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
501 toggleWhisperInfo(viewHolder, message, bubbleColor);
502 viewHolder.image.setVisibility(View.GONE);
503 viewHolder.audioPlayer.setVisibility(View.GONE);
504 viewHolder.download_button.setVisibility(View.VISIBLE);
505 viewHolder.download_button.setText(R.string.show_location);
506 final var attachment = Attachment.of(message);
507 final @DrawableRes int imageResource = MediaAdapter.getImageDrawable(attachment);
508 viewHolder.download_button.setIconResource(imageResource);
509 viewHolder.download_button.setOnClickListener(v -> showLocation(message));
510 }
511
512 private void displayAudioMessage(ViewHolder viewHolder, Message message, final BubbleColor bubbleColor) {
513 toggleWhisperInfo(viewHolder, message, bubbleColor);
514 viewHolder.image.setVisibility(View.GONE);
515 viewHolder.download_button.setVisibility(View.GONE);
516 final RelativeLayout audioPlayer = viewHolder.audioPlayer;
517 audioPlayer.setVisibility(View.VISIBLE);
518 AudioPlayer.ViewHolder.get(audioPlayer).setBubbleColor(bubbleColor);
519 this.audioPlayer.init(audioPlayer, message);
520 }
521
522 private void displayMediaPreviewMessage(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
523 toggleWhisperInfo(viewHolder, message, bubbleColor);
524 viewHolder.download_button.setVisibility(View.GONE);
525 viewHolder.audioPlayer.setVisibility(View.GONE);
526 viewHolder.image.setVisibility(View.VISIBLE);
527 final FileParams params = message.getFileParams();
528 final float target = activity.getResources().getDimension(R.dimen.image_preview_width);
529 final int scaledW;
530 final int scaledH;
531 if (Math.max(params.height, params.width) * metrics.density <= target) {
532 scaledW = (int) (params.width * metrics.density);
533 scaledH = (int) (params.height * metrics.density);
534 } else if (Math.max(params.height, params.width) <= target) {
535 scaledW = params.width;
536 scaledH = params.height;
537 } else if (params.width <= params.height) {
538 scaledW = (int) (params.width / ((double) params.height / target));
539 scaledH = (int) target;
540 } else {
541 scaledW = (int) target;
542 scaledH = (int) (params.height / ((double) params.width / target));
543 }
544 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(scaledW, scaledH);
545 layoutParams.setMargins(0, (int) (metrics.density * 4), 0, (int) (metrics.density * 4));
546 viewHolder.image.setLayoutParams(layoutParams);
547 activity.loadBitmap(message, viewHolder.image);
548 viewHolder.image.setOnClickListener(v -> openDownloadable(message));
549 }
550
551 private void toggleWhisperInfo(ViewHolder viewHolder, final Message message, final BubbleColor bubbleColor) {
552 if (message.isPrivateMessage()) {
553 final String privateMarker;
554 if (message.getStatus() <= Message.STATUS_RECEIVED) {
555 privateMarker = activity.getString(R.string.private_message);
556 } else {
557 Jid cp = message.getCounterpart();
558 privateMarker = activity.getString(R.string.private_message_to, Strings.nullToEmpty(cp == null ? null : cp.getResource()));
559 }
560 final SpannableString body = new SpannableString(privateMarker);
561 body.setSpan(new ForegroundColorSpan(bubbleToOnSurfaceVariant(viewHolder.messageBody, bubbleColor)), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
562 body.setSpan(new StyleSpan(Typeface.BOLD), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
563 viewHolder.messageBody.setText(body);
564 viewHolder.messageBody.setVisibility(View.VISIBLE);
565 } else {
566 viewHolder.messageBody.setVisibility(View.GONE);
567 }
568 }
569
570 private void loadMoreMessages(Conversation conversation) {
571 conversation.setLastClearHistory(0, null);
572 activity.xmppConnectionService.updateConversation(conversation);
573 conversation.setHasMessagesLeftOnServer(true);
574 conversation.setFirstMamReference(null);
575 long timestamp = conversation.getLastMessageTransmitted().getTimestamp();
576 if (timestamp == 0) {
577 timestamp = System.currentTimeMillis();
578 }
579 conversation.messagesLoaded.set(true);
580 MessageArchiveService.Query query = activity.xmppConnectionService.getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
581 if (query != null) {
582 Toast.makeText(activity, R.string.fetching_history_from_server, Toast.LENGTH_LONG).show();
583 } else {
584 Toast.makeText(activity, R.string.not_fetching_history_retention_period, Toast.LENGTH_SHORT).show();
585 }
586 }
587
588 @Override
589 public View getView(final int position, View view, final @NonNull ViewGroup parent) {
590 final Message message = getItem(position);
591 final boolean omemoEncryption = message.getEncryption() == Message.ENCRYPTION_AXOLOTL;
592 final boolean isInValidSession = message.isValidInSession() && (!omemoEncryption || message.isTrusted());
593 final Conversational conversation = message.getConversation();
594 final Account account = conversation.getAccount();
595 final int type = getItemViewType(position);
596 ViewHolder viewHolder;
597 if (view == null) {
598 viewHolder = new ViewHolder();
599 switch (type) {
600 case DATE_SEPARATOR:
601 view = activity.getLayoutInflater().inflate(R.layout.item_message_date_bubble, parent, false);
602 viewHolder.status_message = view.findViewById(R.id.message_body);
603 viewHolder.message_box = view.findViewById(R.id.message_box);
604 break;
605 case RTP_SESSION:
606 view = activity.getLayoutInflater().inflate(R.layout.item_message_rtp_session, parent, false);
607 viewHolder.status_message = view.findViewById(R.id.message_body);
608 viewHolder.message_box = view.findViewById(R.id.message_box);
609 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
610 break;
611 case SENT:
612 view = activity.getLayoutInflater().inflate(R.layout.item_message_sent, parent, false);
613 viewHolder.message_box = view.findViewById(R.id.message_box);
614 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
615 viewHolder.download_button = view.findViewById(R.id.download_button);
616 viewHolder.indicator = view.findViewById(R.id.security_indicator);
617 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
618 viewHolder.image = view.findViewById(R.id.message_image);
619 viewHolder.messageBody = view.findViewById(R.id.message_body);
620 viewHolder.time = view.findViewById(R.id.message_time);
621 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
622 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
623 break;
624 case RECEIVED:
625 view = activity.getLayoutInflater().inflate(R.layout.item_message_received, parent, false);
626 viewHolder.message_box = view.findViewById(R.id.message_box);
627 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
628 viewHolder.download_button = view.findViewById(R.id.download_button);
629 viewHolder.indicator = view.findViewById(R.id.security_indicator);
630 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
631 viewHolder.image = view.findViewById(R.id.message_image);
632 viewHolder.messageBody = view.findViewById(R.id.message_body);
633 viewHolder.time = view.findViewById(R.id.message_time);
634 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
635 viewHolder.encryption = view.findViewById(R.id.message_encryption);
636 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
637 break;
638 case STATUS:
639 view = activity.getLayoutInflater().inflate(R.layout.item_message_status, parent, false);
640 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
641 viewHolder.status_message = view.findViewById(R.id.status_message);
642 viewHolder.load_more_messages = view.findViewById(R.id.load_more_messages);
643 break;
644 default:
645 throw new AssertionError("Unknown view type");
646 }
647 view.setTag(viewHolder);
648 } else {
649 viewHolder = (ViewHolder) view.getTag();
650 if (viewHolder == null) {
651 return view;
652 }
653 }
654
655 final boolean colorfulBackground = this.colorfulChatBubbles;
656 final BubbleColor bubbleColor;
657 if (type == RECEIVED) {
658 if (isInValidSession) {
659 bubbleColor = colorfulBackground ? BubbleColor.SECONDARY : BubbleColor.SURFACE;
660 } else {
661 bubbleColor = BubbleColor.WARNING;
662 }
663 } else {
664 bubbleColor = colorfulBackground ? BubbleColor.TERTIARY : BubbleColor.SURFACE;
665 }
666
667 if (type == DATE_SEPARATOR) {
668 if (UIHelper.today(message.getTimeSent())) {
669 viewHolder.status_message.setText(R.string.today);
670 } else if (UIHelper.yesterday(message.getTimeSent())) {
671 viewHolder.status_message.setText(R.string.yesterday);
672 } else {
673 viewHolder.status_message.setText(DateUtils.formatDateTime(activity, message.getTimeSent(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
674 }
675 if (colorfulBackground) {
676 setBackgroundTint(viewHolder.message_box,BubbleColor.PRIMARY);
677 setTextColor(viewHolder.status_message, BubbleColor.PRIMARY);
678 } else {
679 setBackgroundTint(viewHolder.message_box,BubbleColor.SURFACE);
680 setTextColor(viewHolder.status_message, BubbleColor.SURFACE);
681 }
682 return view;
683 } else if (type == RTP_SESSION) {
684 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
685 final RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
686 final long duration = rtpSessionStatus.duration;
687 if (received) {
688 if (duration > 0) {
689 viewHolder.status_message.setText(activity.getString(R.string.incoming_call_duration_timestamp, TimeFrameUtils.resolve(activity, duration), UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent())));
690 } else if (rtpSessionStatus.successful) {
691 viewHolder.status_message.setText(R.string.incoming_call);
692 } else {
693 viewHolder.status_message.setText(activity.getString(R.string.missed_call_timestamp, UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent())));
694 }
695 } else {
696 if (duration > 0) {
697 viewHolder.status_message.setText(activity.getString(R.string.outgoing_call_duration_timestamp, TimeFrameUtils.resolve(activity, duration), UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent())));
698 } else {
699 viewHolder.status_message.setText(activity.getString(R.string.outgoing_call_timestamp, UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent())));
700 }
701 }
702 if (colorfulBackground) {
703 setBackgroundTint(viewHolder.message_box,BubbleColor.SECONDARY);
704 setTextColor(viewHolder.status_message, BubbleColor.SECONDARY);
705 setImageTint(viewHolder.indicatorReceived, BubbleColor.SECONDARY);
706 } else {
707 setBackgroundTint(viewHolder.message_box,BubbleColor.SURFACE);
708 setTextColor(viewHolder.status_message, BubbleColor.SURFACE);
709 setImageTint(viewHolder.indicatorReceived, BubbleColor.SURFACE);
710 }
711 viewHolder.indicatorReceived.setImageResource(RtpSessionStatus.getDrawable(received, rtpSessionStatus.successful));
712 return view;
713 } else if (type == STATUS) {
714 if ("LOAD_MORE".equals(message.getBody())) {
715 viewHolder.status_message.setVisibility(View.GONE);
716 viewHolder.contact_picture.setVisibility(View.GONE);
717 viewHolder.load_more_messages.setVisibility(View.VISIBLE);
718 viewHolder.load_more_messages.setOnClickListener(v -> loadMoreMessages((Conversation) message.getConversation()));
719 } else {
720 viewHolder.status_message.setVisibility(View.VISIBLE);
721 viewHolder.load_more_messages.setVisibility(View.GONE);
722 viewHolder.status_message.setText(message.getBody());
723 boolean showAvatar;
724 if (conversation.getMode() == Conversation.MODE_SINGLE) {
725 showAvatar = true;
726 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
727 } else if (message.getCounterpart() != null || message.getTrueCounterpart() != null || (message.getCounterparts() != null && message.getCounterparts().size() > 0)) {
728 showAvatar = true;
729 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
730 } else {
731 showAvatar = false;
732 }
733 if (showAvatar) {
734 viewHolder.contact_picture.setAlpha(0.5f);
735 viewHolder.contact_picture.setVisibility(View.VISIBLE);
736 } else {
737 viewHolder.contact_picture.setVisibility(View.GONE);
738 }
739 }
740 return view;
741 } else {
742 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar);
743 }
744
745 resetClickListener(viewHolder.message_box, viewHolder.messageBody);
746
747 viewHolder.contact_picture.setOnClickListener(v -> {
748 if (MessageAdapter.this.mOnContactPictureClickedListener != null) {
749 MessageAdapter.this.mOnContactPictureClickedListener
750 .onContactPictureClicked(message);
751 }
752
753 });
754 viewHolder.contact_picture.setOnLongClickListener(v -> {
755 if (MessageAdapter.this.mOnContactPictureLongClickedListener != null) {
756 MessageAdapter.this.mOnContactPictureLongClickedListener
757 .onContactPictureLongClicked(v, message);
758 return true;
759 } else {
760 return false;
761 }
762 });
763
764 final Transferable transferable = message.getTransferable();
765 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(message);
766 if (unInitiatedButKnownSize || message.isDeleted() || (transferable != null && transferable.getStatus() != Transferable.STATUS_UPLOADING)) {
767 if (unInitiatedButKnownSize || transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER) {
768 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, message)), bubbleColor);
769 } else if (transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER_CHECK_FILESIZE) {
770 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.check_x_filesize, UIHelper.getFileDescriptionString(activity, message)), bubbleColor);
771 } else {
772 displayInfoMessage(viewHolder, UIHelper.getMessagePreview(activity, message).first, bubbleColor);
773 }
774 } else if (message.isFileOrImage() && message.getEncryption() != Message.ENCRYPTION_PGP && message.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED) {
775 if (message.getFileParams().width > 0 && message.getFileParams().height > 0) {
776 displayMediaPreviewMessage(viewHolder, message, bubbleColor);
777 } else if (message.getFileParams().runtime > 0) {
778 displayAudioMessage(viewHolder, message, bubbleColor);
779 } else {
780 displayOpenableMessage(viewHolder, message, bubbleColor);
781 }
782 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
783 if (account.isPgpDecryptionServiceConnected()) {
784 if (conversation instanceof Conversation && !account.hasPendingPgpIntent((Conversation) conversation)) {
785 displayInfoMessage(viewHolder, activity.getString(R.string.message_decrypting), bubbleColor);
786 } else {
787 displayInfoMessage(viewHolder, activity.getString(R.string.pgp_message), bubbleColor);
788 }
789 } else {
790 displayInfoMessage(viewHolder, activity.getString(R.string.install_openkeychain), bubbleColor);
791 viewHolder.message_box.setOnClickListener(this::promptOpenKeychainInstall);
792 viewHolder.messageBody.setOnClickListener(this::promptOpenKeychainInstall);
793 }
794 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
795 displayInfoMessage(viewHolder, activity.getString(R.string.decryption_failed), bubbleColor);
796 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
797 displayInfoMessage(viewHolder, activity.getString(R.string.not_encrypted_for_this_device), bubbleColor);
798 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
799 displayInfoMessage(viewHolder, activity.getString(R.string.omemo_decryption_failed), bubbleColor);
800 } else {
801 if (message.isGeoUri()) {
802 displayLocationMessage(viewHolder, message, bubbleColor);
803 } else if (message.bodyIsOnlyEmojis() && message.getType() != Message.TYPE_PRIVATE) {
804 displayEmojiMessage(viewHolder, message.getBody().trim(), bubbleColor);
805 } else if (message.treatAsDownloadable()) {
806 try {
807 final URI uri = new URI(message.getBody());
808 displayDownloadableMessage(viewHolder,
809 message,
810 activity.getString(R.string.check_x_filesize_on_host,
811 UIHelper.getFileDescriptionString(activity, message),
812 uri.getHost()),
813 bubbleColor);
814 } catch (Exception e) {
815 displayDownloadableMessage(viewHolder,
816 message,
817 activity.getString(R.string.check_x_filesize,
818 UIHelper.getFileDescriptionString(activity, message)),
819 bubbleColor);
820 }
821 } else {
822 displayTextMessage(viewHolder, message, bubbleColor, type);
823 }
824 }
825
826 setBackgroundTint(viewHolder.message_box, bubbleColor);
827 setTextColor(viewHolder.messageBody, bubbleColor);
828
829 if (type == RECEIVED) {
830 setTextColor(viewHolder.encryption, bubbleColor);
831 if (isInValidSession) {
832 viewHolder.encryption.setVisibility(View.GONE);
833 } else {
834 viewHolder.encryption.setVisibility(View.VISIBLE);
835 if (omemoEncryption && !message.isTrusted()) {
836 viewHolder.encryption.setText(R.string.not_trusted);
837 } else {
838 viewHolder.encryption.setText(CryptoHelper.encryptionTypeToText(message.getEncryption()));
839 }
840 }
841 }
842
843 displayStatus(viewHolder, message, type, bubbleColor);
844
845 return view;
846 }
847
848 private void promptOpenKeychainInstall(View view) {
849 activity.showInstallPgpDialog();
850 }
851
852 public FileBackend getFileBackend() {
853 return activity.xmppConnectionService.getFileBackend();
854 }
855
856 public void stopAudioPlayer() {
857 audioPlayer.stop();
858 }
859
860 public void unregisterListenerInAudioPlayer() {
861 audioPlayer.unregisterListener();
862 }
863
864 public void startStopPending() {
865 audioPlayer.startStopPending();
866 }
867
868 public void openDownloadable(Message message) {
869 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
870 ConversationFragment.registerPendingMessage(activity, message);
871 ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ConversationsActivity.REQUEST_OPEN_MESSAGE);
872 return;
873 }
874 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
875 ViewUtil.view(activity, file);
876 }
877
878 private void showLocation(Message message) {
879 for (Intent intent : GeoHelper.createGeoIntentsFromMessage(activity, message)) {
880 if (intent.resolveActivity(getContext().getPackageManager()) != null) {
881 getContext().startActivity(intent);
882 return;
883 }
884 }
885 Toast.makeText(activity, R.string.no_application_found_to_display_location, Toast.LENGTH_SHORT).show();
886 }
887
888 public void updatePreferences() {
889 final AppSettings appSettings = new AppSettings(activity);
890 this.colorfulChatBubbles = appSettings.isColorfulChatBubbles();
891 }
892
893
894 public void setHighlightedTerm(List<String> terms) {
895 this.highlightedTerm = terms == null ? null : StylingHelper.filterHighlightedWords(terms);
896 }
897
898 public interface OnContactPictureClicked {
899 void onContactPictureClicked(Message message);
900 }
901
902 public interface OnContactPictureLongClicked {
903 void onContactPictureLongClicked(View v, Message message);
904 }
905
906 private static void setBackgroundTint(final View view, final BubbleColor bubbleColor) {
907 view.setBackgroundTintList(bubbleToColorStateList(view, bubbleColor));
908 }
909
910 private static ColorStateList bubbleToColorStateList(final View view, final BubbleColor bubbleColor) {
911 final @AttrRes int colorAttributeResId = switch (bubbleColor) {
912 case SURFACE -> com.google.android.material.R.attr.colorSurfaceContainerHigh;
913 case PRIMARY -> com.google.android.material.R.attr.colorPrimaryContainer;
914 case SECONDARY -> com.google.android.material.R.attr.colorSecondaryContainer;
915 case TERTIARY -> com.google.android.material.R.attr.colorTertiaryContainer;
916 case WARNING -> com.google.android.material.R.attr.colorErrorContainer;
917 };
918 return ColorStateList.valueOf(MaterialColors.getColor(view,colorAttributeResId));
919 }
920
921 public static void setImageTint(final ImageView imageView, final BubbleColor bubbleColor) {
922 ImageViewCompat.setImageTintList(imageView,bubbleToOnSurfaceColorStateList(imageView, bubbleColor));
923 }
924
925 public static void setTextColor(final TextView textView, final BubbleColor bubbleColor) {
926 textView.setTextColor(bubbleToOnSurfaceColor(textView, bubbleColor));
927 }
928
929 private static @ColorInt int bubbleToOnSurfaceVariant(final View view, final BubbleColor bubbleColor) {
930 final @AttrRes int colorAttributeResId;
931 if (bubbleColor == BubbleColor.SURFACE) {
932 colorAttributeResId = com.google.android.material.R.attr.colorOnSurfaceVariant;
933 } else {
934 colorAttributeResId = bubbleToOnSurface(bubbleColor);
935 }
936 return MaterialColors.getColor(view,colorAttributeResId);
937 }
938
939 private static @ColorInt int bubbleToOnSurfaceColor(final View view, final BubbleColor bubbleColor) {
940 return MaterialColors.getColor(view, bubbleToOnSurface(bubbleColor));
941 }
942
943 public static ColorStateList bubbleToOnSurfaceColorStateList(final View view, final BubbleColor bubbleColor) {
944 return ColorStateList.valueOf(bubbleToOnSurfaceColor(view, bubbleColor));
945 }
946
947 private static @AttrRes int bubbleToOnSurface(final BubbleColor bubbleColor) {
948 return switch (bubbleColor) {
949 case SURFACE -> com.google.android.material.R.attr.colorOnSurface;
950 case PRIMARY -> com.google.android.material.R.attr.colorOnPrimaryContainer;
951 case SECONDARY -> com.google.android.material.R.attr.colorOnSecondaryContainer;
952 case TERTIARY -> com.google.android.material.R.attr.colorOnTertiaryContainer;
953 case WARNING -> com.google.android.material.R.attr.colorOnErrorContainer;
954 };
955 }
956
957 public enum BubbleColor {
958 SURFACE, PRIMARY, SECONDARY, TERTIARY, WARNING
959 }
960
961 private static class ViewHolder {
962
963 public MaterialButton load_more_messages;
964 public ImageView edit_indicator;
965 public RelativeLayout audioPlayer;
966 protected LinearLayout message_box;
967 protected MaterialButton download_button;
968 protected ImageView image;
969 protected ImageView indicator;
970 protected ImageView indicatorReceived;
971 protected TextView time;
972 protected TextView messageBody;
973 protected ImageView contact_picture;
974 protected TextView status_message;
975 protected TextView encryption;
976 }
977}