1package eu.siacs.conversations.ui.adapter;
2
3import android.Manifest;
4import android.app.Activity;
5import android.content.Intent;
6import android.content.SharedPreferences;
7import android.content.pm.PackageManager;
8import android.graphics.PorterDuff;
9import android.graphics.drawable.Drawable;
10import android.graphics.Typeface;
11import android.net.Uri;
12import android.os.AsyncTask;
13import android.preference.PreferenceManager;
14import android.text.Spannable;
15import android.text.SpannableString;
16import android.text.SpannableStringBuilder;
17import android.text.style.ImageSpan;
18import android.text.style.ClickableSpan;
19import android.text.format.DateUtils;
20import android.text.style.ForegroundColorSpan;
21import android.text.style.RelativeSizeSpan;
22import android.text.style.StyleSpan;
23import android.text.style.URLSpan;
24import android.util.DisplayMetrics;
25import android.view.MotionEvent;
26import android.view.View;
27import android.view.ViewGroup;
28import android.view.WindowManager;
29import android.widget.ArrayAdapter;
30import android.widget.Button;
31import android.widget.ImageView;
32import android.widget.LinearLayout;
33import android.widget.ListAdapter;
34import android.widget.ListView;
35import android.widget.RelativeLayout;
36import android.widget.TextView;
37import android.widget.Toast;
38
39import androidx.core.app.ActivityCompat;
40import androidx.core.content.ContextCompat;
41import androidx.core.content.res.ResourcesCompat;
42
43import com.cheogram.android.BobTransfer;
44import com.cheogram.android.SwipeDetector;
45
46import com.google.common.base.Strings;
47
48import com.lelloman.identicon.view.GithubIdenticonView;
49
50import java.io.IOException;
51import java.net.URI;
52import java.net.URISyntaxException;
53import java.security.NoSuchAlgorithmException;
54import java.util.List;
55import java.util.Locale;
56import java.util.regex.Matcher;
57import java.util.regex.Pattern;
58
59import io.ipfs.cid.Cid;
60
61import me.saket.bettermovementmethod.BetterLinkMovementMethod;
62
63import eu.siacs.conversations.Config;
64import eu.siacs.conversations.R;
65import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
66import eu.siacs.conversations.entities.Account;
67import eu.siacs.conversations.entities.Contact;
68import eu.siacs.conversations.entities.Conversation;
69import eu.siacs.conversations.entities.Conversational;
70import eu.siacs.conversations.entities.DownloadableFile;
71import eu.siacs.conversations.entities.Message.FileParams;
72import eu.siacs.conversations.entities.Message;
73import eu.siacs.conversations.entities.Roster;
74import eu.siacs.conversations.entities.RtpSessionStatus;
75import eu.siacs.conversations.entities.Transferable;
76import eu.siacs.conversations.persistance.FileBackend;
77import eu.siacs.conversations.services.MessageArchiveService;
78import eu.siacs.conversations.services.NotificationService;
79import eu.siacs.conversations.ui.ConversationFragment;
80import eu.siacs.conversations.ui.ConversationsActivity;
81import eu.siacs.conversations.ui.XmppActivity;
82import eu.siacs.conversations.ui.service.AudioPlayer;
83import eu.siacs.conversations.ui.text.DividerSpan;
84import eu.siacs.conversations.ui.text.QuoteSpan;
85import eu.siacs.conversations.ui.util.AvatarWorkerTask;
86import eu.siacs.conversations.ui.util.MyLinkify;
87import eu.siacs.conversations.ui.util.QuoteHelper;
88import eu.siacs.conversations.ui.util.ShareUtil;
89import eu.siacs.conversations.ui.util.StyledAttributes;
90import eu.siacs.conversations.ui.util.ViewUtil;
91import eu.siacs.conversations.utils.CryptoHelper;
92import eu.siacs.conversations.utils.Emoticons;
93import eu.siacs.conversations.utils.GeoHelper;
94import eu.siacs.conversations.utils.MessageUtils;
95import eu.siacs.conversations.utils.StylingHelper;
96import eu.siacs.conversations.utils.TimeFrameUtils;
97import eu.siacs.conversations.utils.UIHelper;
98import eu.siacs.conversations.xmpp.Jid;
99import eu.siacs.conversations.xmpp.mam.MamReference;
100import eu.siacs.conversations.xml.Element;
101
102public class MessageAdapter extends ArrayAdapter<Message> {
103
104 public static final String DATE_SEPARATOR_BODY = "DATE_SEPARATOR";
105 private static final int SENT = 0;
106 private static final int RECEIVED = 1;
107 private static final int STATUS = 2;
108 private static final int DATE_SEPARATOR = 3;
109 private static final int RTP_SESSION = 4;
110 private final XmppActivity activity;
111 private final AudioPlayer audioPlayer;
112 private List<String> highlightedTerm = null;
113 private final DisplayMetrics metrics;
114 private OnContactPictureClicked mOnContactPictureClickedListener;
115 private OnContactPictureClicked mOnMessageBoxClickedListener;
116 private OnContactPictureClicked mOnMessageBoxSwipedListener;
117 private OnContactPictureLongClicked mOnContactPictureLongClickedListener;
118 private OnInlineImageLongClicked mOnInlineImageLongClickedListener;
119 private boolean mUseGreenBackground = false;
120 private final boolean mForceNames;
121
122 public MessageAdapter(final XmppActivity activity, final List<Message> messages, final boolean forceNames) {
123 super(activity, 0, messages);
124 this.audioPlayer = new AudioPlayer(this);
125 this.activity = activity;
126 metrics = getContext().getResources().getDisplayMetrics();
127 updatePreferences();
128 this.mForceNames = forceNames;
129 }
130
131 public MessageAdapter(final XmppActivity activity, final List<Message> messages) {
132 this(activity, messages, false);
133 }
134
135 private static void resetClickListener(View... views) {
136 for (View view : views) {
137 if (view != null) view.setOnClickListener(null);
138 }
139 }
140
141 public void flagScreenOn() {
142 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
143 }
144
145 public void flagScreenOff() {
146 activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
147 }
148
149 public void setVolumeControl(final int stream) {
150 activity.setVolumeControlStream(stream);
151 }
152
153 public void setOnContactPictureClicked(OnContactPictureClicked listener) {
154 this.mOnContactPictureClickedListener = listener;
155 }
156
157 public void setOnMessageBoxClicked(OnContactPictureClicked listener) {
158 this.mOnMessageBoxClickedListener = listener;
159 }
160
161 public void setOnMessageBoxSwiped(OnContactPictureClicked listener) {
162 this.mOnMessageBoxSwipedListener = listener;
163 }
164
165 public Activity getActivity() {
166 return activity;
167 }
168
169 public void setOnContactPictureLongClicked(
170 OnContactPictureLongClicked listener) {
171 this.mOnContactPictureLongClickedListener = listener;
172 }
173
174 public void setOnInlineImageLongClicked(OnInlineImageLongClicked listener) {
175 this.mOnInlineImageLongClickedListener = listener;
176 }
177
178 @Override
179 public int getViewTypeCount() {
180 return 5;
181 }
182
183 private int getItemViewType(Message message) {
184 if (message.getType() == Message.TYPE_STATUS) {
185 if (DATE_SEPARATOR_BODY.equals(message.getBody())) {
186 return DATE_SEPARATOR;
187 } else {
188 return STATUS;
189 }
190 } else if (message.getType() == Message.TYPE_RTP_SESSION) {
191 return RTP_SESSION;
192 } else if (message.getStatus() <= Message.STATUS_RECEIVED) {
193 return RECEIVED;
194 } else {
195 return SENT;
196 }
197 }
198
199 @Override
200 public int getItemViewType(int position) {
201 return this.getItemViewType(getItem(position));
202 }
203
204 private int getMessageTextColor(boolean onDark, boolean primary) {
205 if (onDark) {
206 return ContextCompat.getColor(activity, primary ? R.color.white : R.color.white70);
207 } else {
208 return ContextCompat.getColor(activity, primary ? R.color.black87 : R.color.black54);
209 }
210 }
211
212 private void displayStatus(ViewHolder viewHolder, Message message, int type, boolean darkBackground) {
213 String filesize = null;
214 String info = null;
215 boolean error = false;
216 if (viewHolder.indicatorReceived != null) {
217 viewHolder.indicatorReceived.setVisibility(View.GONE);
218 }
219
220 if (viewHolder.edit_indicator != null) {
221 if (message.edited() && message.getModerated() == null) {
222 viewHolder.edit_indicator.setVisibility(View.VISIBLE);
223 viewHolder.edit_indicator.setImageResource(darkBackground ? R.drawable.ic_mode_edit_white_18dp : R.drawable.ic_mode_edit_black_18dp);
224 viewHolder.edit_indicator.setAlpha(darkBackground ? 0.7f : 0.57f);
225 } else {
226 viewHolder.edit_indicator.setVisibility(View.GONE);
227 }
228 }
229 final Transferable transferable = message.getTransferable();
230 boolean multiReceived = message.getConversation().getMode() == Conversation.MODE_MULTI
231 && message.getMergedStatus() <= Message.STATUS_RECEIVED;
232 if (message.isFileOrImage() || transferable != null || MessageUtils.unInitiatedButKnownSize(message)) {
233 FileParams params = message.getFileParams();
234 filesize = params.size != null ? UIHelper.filesizeToString(params.size) : null;
235 if (transferable != null && (transferable.getStatus() == Transferable.STATUS_FAILED || transferable.getStatus() == Transferable.STATUS_CANCELLED)) {
236 error = true;
237 }
238 }
239 switch (message.getMergedStatus()) {
240 case Message.STATUS_WAITING:
241 info = getContext().getString(R.string.waiting);
242 break;
243 case Message.STATUS_UNSEND:
244 if (transferable != null) {
245 info = getContext().getString(R.string.sending_file, transferable.getProgress());
246 } else {
247 info = getContext().getString(R.string.sending);
248 }
249 break;
250 case Message.STATUS_OFFERED:
251 info = getContext().getString(R.string.offering);
252 break;
253 case Message.STATUS_SEND_RECEIVED:
254 case Message.STATUS_SEND_DISPLAYED:
255 viewHolder.indicatorReceived.setImageResource(darkBackground ? R.drawable.ic_done_white_18dp : R.drawable.ic_done_black_18dp);
256 viewHolder.indicatorReceived.setAlpha(darkBackground ? 0.7f : 0.57f);
257 viewHolder.indicatorReceived.setVisibility(View.VISIBLE);
258 break;
259 case Message.STATUS_SEND_FAILED:
260 final String errorMessage = message.getErrorMessage();
261 if (Message.ERROR_MESSAGE_CANCELLED.equals(errorMessage)) {
262 info = getContext().getString(R.string.cancelled);
263 } else if (errorMessage != null) {
264 final String[] errorParts = errorMessage.split("\\u001f", 2);
265 if (errorParts.length == 2) {
266 switch (errorParts[0]) {
267 case "file-too-large":
268 info = getContext().getString(R.string.file_too_large);
269 break;
270 default:
271 info = getContext().getString(R.string.send_failed);
272 break;
273 }
274 } else {
275 info = getContext().getString(R.string.send_failed);
276 }
277 } else {
278 info = getContext().getString(R.string.send_failed);
279 }
280 error = true;
281 break;
282 default:
283 if (mForceNames || multiReceived || (message.getTrueCounterpart() != null && message.getContact() != null)) {
284 info = UIHelper.getMessageDisplayName(message);
285 }
286 break;
287 }
288 if (error && type == SENT) {
289 if (darkBackground) {
290 viewHolder.time.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Caption_Warning_OnDark);
291 } else {
292 viewHolder.time.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Caption_Warning);
293 }
294 } else {
295 if (darkBackground) {
296 viewHolder.time.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Caption_OnDark);
297 } else {
298 viewHolder.time.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Caption);
299 }
300 viewHolder.time.setTextColor(this.getMessageTextColor(darkBackground, false));
301 }
302 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
303 viewHolder.indicator.setVisibility(View.GONE);
304 } else {
305 boolean verified = false;
306 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
307 final FingerprintStatus status = message.getConversation()
308 .getAccount().getAxolotlService().getFingerprintTrust(
309 message.getFingerprint());
310 if (status != null && status.isVerified()) {
311 verified = true;
312 }
313 }
314 if (verified) {
315 viewHolder.indicator.setImageResource(darkBackground ? R.drawable.ic_verified_user_white_18dp : R.drawable.ic_verified_user_black_18dp);
316 } else {
317 viewHolder.indicator.setImageResource(darkBackground ? R.drawable.ic_lock_white_18dp : R.drawable.ic_lock_black_18dp);
318 }
319 if (darkBackground) {
320 viewHolder.indicator.setAlpha(0.7f);
321 } else {
322 viewHolder.indicator.setAlpha(0.57f);
323 }
324 viewHolder.indicator.setVisibility(View.VISIBLE);
325 }
326
327 final String formattedTime = UIHelper.readableTimeDifferenceFull(getContext(), message.getMergedTimeSent());
328 final String bodyLanguage = message.getBodyLanguage();
329 final String bodyLanguageInfo = bodyLanguage == null ? "" : String.format(" \u00B7 %s", bodyLanguage.toUpperCase(Locale.US));
330 if (message.getStatus() <= Message.STATUS_RECEIVED) {
331 if ((filesize != null) && (info != null)) {
332 viewHolder.time.setText(formattedTime + " \u00B7 " + filesize + " \u00B7 " + info + bodyLanguageInfo);
333 } else if ((filesize == null) && (info != null)) {
334 viewHolder.time.setText(formattedTime + " \u00B7 " + info + bodyLanguageInfo);
335 } else if ((filesize != null) && (info == null)) {
336 viewHolder.time.setText(formattedTime + " \u00B7 " + filesize + bodyLanguageInfo);
337 } else {
338 viewHolder.time.setText(formattedTime + bodyLanguageInfo);
339 }
340 } else {
341 if ((filesize != null) && (info != null)) {
342 viewHolder.time.setText(filesize + " \u00B7 " + info + bodyLanguageInfo);
343 } else if ((filesize == null) && (info != null)) {
344 if (error) {
345 viewHolder.time.setText(info + " \u00B7 " + formattedTime + bodyLanguageInfo);
346 } else {
347 viewHolder.time.setText(info);
348 }
349 } else if ((filesize != null) && (info == null)) {
350 viewHolder.time.setText(filesize + " \u00B7 " + formattedTime + bodyLanguageInfo);
351 } else {
352 viewHolder.time.setText(formattedTime + bodyLanguageInfo);
353 }
354 }
355 }
356
357 private void displayInfoMessage(ViewHolder viewHolder, CharSequence text, boolean darkBackground, final Message message, int type) {
358 displayDownloadableMessage(viewHolder, message, "", darkBackground, type);
359 int imageVisibility = viewHolder.image.getVisibility();
360 displayInfoMessage(viewHolder, text, darkBackground);
361 viewHolder.image.setVisibility(imageVisibility);
362 }
363
364 private void displayInfoMessage(ViewHolder viewHolder, CharSequence text, boolean darkBackground) {
365 viewHolder.download_button.setVisibility(View.GONE);
366 viewHolder.audioPlayer.setVisibility(View.GONE);
367 viewHolder.image.setVisibility(View.GONE);
368 viewHolder.messageBody.setVisibility(View.VISIBLE);
369 viewHolder.messageBody.setText(text);
370 if (darkBackground) {
371 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1_Secondary_OnDark);
372 } else {
373 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1_Secondary);
374 }
375 viewHolder.messageBody.setTextIsSelectable(false);
376 }
377
378 private void displayEmojiMessage(final ViewHolder viewHolder, final String body, final boolean darkBackground) {
379 viewHolder.download_button.setVisibility(View.GONE);
380 viewHolder.audioPlayer.setVisibility(View.GONE);
381 viewHolder.image.setVisibility(View.GONE);
382 viewHolder.messageBody.setVisibility(View.VISIBLE);
383 if (darkBackground) {
384 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1_Emoji_OnDark);
385 } else {
386 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1_Emoji);
387 }
388 Spannable span = new SpannableString(body);
389 float size = Emoticons.isEmoji(body) ? 3.0f : 2.0f;
390 span.setSpan(new RelativeSizeSpan(size), 0, body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
391 viewHolder.messageBody.setText(span);
392 }
393
394 private void applyQuoteSpan(SpannableStringBuilder body, int start, int end, boolean darkBackground) {
395 if (start > 1 && !"\n\n".equals(body.subSequence(start - 2, start).toString())) {
396 body.insert(start++, "\n");
397 body.setSpan(
398 new DividerSpan(false),
399 start - ("\n".equals(body.subSequence(start - 2, start - 1).toString()) ? 2 : 1),
400 start,
401 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
402 );
403 end++;
404 }
405 if (end < body.length() - 1 && !"\n\n".equals(body.subSequence(end, end + 2).toString())) {
406 body.insert(end, "\n");
407 body.setSpan(
408 new DividerSpan(false),
409 end,
410 end + ("\n".equals(body.subSequence(end + 1, end + 2).toString()) ? 2 : 1),
411 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
412 );
413 }
414 int color = darkBackground ? this.getMessageTextColor(darkBackground, false)
415 : ContextCompat.getColor(activity, R.color.green700_desaturated);
416 DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
417 body.setSpan(new QuoteSpan(color, metrics), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
418 }
419
420 /**
421 * Applies QuoteSpan to group of lines which starts with > or » characters.
422 * Appends likebreaks and applies DividerSpan to them to show a padding between quote and text.
423 */
424 public boolean handleTextQuotes(SpannableStringBuilder body, boolean darkBackground) {
425 boolean startsWithQuote = false;
426 int quoteDepth = 1;
427 while (QuoteHelper.bodyContainsQuoteStart(body) && quoteDepth <= Config.QUOTE_MAX_DEPTH) {
428 char previous = '\n';
429 int lineStart = -1;
430 int lineTextStart = -1;
431 int quoteStart = -1;
432 for (int i = 0; i <= body.length(); i++) {
433 char current = body.length() > i ? body.charAt(i) : '\n';
434 if (lineStart == -1) {
435 if (previous == '\n') {
436 if (i < body.length() && QuoteHelper.isPositionQuoteStart(body, i)) {
437 // Line start with quote
438 lineStart = i;
439 if (quoteStart == -1) quoteStart = i;
440 if (i == 0) startsWithQuote = true;
441 } else if (quoteStart >= 0) {
442 // Line start without quote, apply spans there
443 applyQuoteSpan(body, quoteStart, i - 1, darkBackground);
444 quoteStart = -1;
445 }
446 }
447 } else {
448 // Remove extra spaces between > and first character in the line
449 // > character will be removed too
450 if (current != ' ' && lineTextStart == -1) {
451 lineTextStart = i;
452 }
453 if (current == '\n') {
454 body.delete(lineStart, lineTextStart);
455 i -= lineTextStart - lineStart;
456 if (i == lineStart) {
457 // Avoid empty lines because span over empty line can be hidden
458 body.insert(i++, " ");
459 }
460 lineStart = -1;
461 lineTextStart = -1;
462 }
463 }
464 previous = current;
465 }
466 if (quoteStart >= 0) {
467 // Apply spans to finishing open quote
468 applyQuoteSpan(body, quoteStart, body.length(), darkBackground);
469 }
470 quoteDepth++;
471 }
472 return startsWithQuote;
473 }
474
475 private void displayTextMessage(final ViewHolder viewHolder, final Message message, boolean darkBackground, int type) {
476 viewHolder.download_button.setVisibility(View.GONE);
477 viewHolder.image.setVisibility(View.GONE);
478 viewHolder.audioPlayer.setVisibility(View.GONE);
479 viewHolder.messageBody.setVisibility(View.GONE);
480
481 if (darkBackground) {
482 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1_OnDark);
483 } else {
484 viewHolder.messageBody.setTextAppearance(getContext(), R.style.TextAppearance_Conversations_Body1);
485 }
486 viewHolder.messageBody.setHighlightColor(ContextCompat.getColor(activity, darkBackground
487 ? (type == SENT || !mUseGreenBackground ? R.color.black26 : R.color.grey800) : R.color.grey500));
488 viewHolder.messageBody.setTypeface(null, Typeface.NORMAL);
489
490 if (message.getBody() != null && !message.getBody().equals("")) {
491 viewHolder.messageBody.setVisibility(View.VISIBLE);
492 final String nick = UIHelper.getMessageDisplayName(message);
493 Drawable fallbackImg = ResourcesCompat.getDrawable(activity.getResources(), activity.getThemeResource(R.attr.ic_attach_photo, R.drawable.ic_attach_photo), null);
494 fallbackImg.setBounds(FileBackend.rectForSize(fallbackImg.getIntrinsicWidth(), fallbackImg.getIntrinsicHeight(), (int) (metrics.density * 32)));
495 SpannableStringBuilder body = message.getMergedBody((cid) -> {
496 try {
497 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
498 if (f == null || !f.canRead()) {
499 if (!message.trusted() && !message.getConversation().canInferPresence()) return null;
500
501 try {
502 new BobTransfer(BobTransfer.uri(cid), message.getConversation().getAccount(), message.getCounterpart(), activity.xmppConnectionService).start();
503 } catch (final NoSuchAlgorithmException | URISyntaxException e) { }
504 return null;
505 }
506
507 Drawable d = activity.xmppConnectionService.getFileBackend().getThumbnail(f, activity.getResources(), (int) (metrics.density * 288), true);
508 if (d == null) {
509 new ThumbnailTask().execute(f);
510 } else {
511 d = d.getConstantState().newDrawable();
512 d.setBounds(FileBackend.rectForSize(d.getIntrinsicWidth(), d.getIntrinsicHeight(), (int) (metrics.density * 32)));
513 }
514 return d;
515 } catch (final IOException e) {
516 return fallbackImg;
517 }
518 }, fallbackImg);
519 boolean hasMeCommand = message.hasMeCommand();
520 if (hasMeCommand) {
521 body = body.replace(0, Message.ME_COMMAND.length(), nick + " ");
522 }
523 if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
524 body = new SpannableStringBuilder(body, 0, Config.MAX_DISPLAY_MESSAGE_CHARS);
525 body.append("\u2026");
526 }
527 Message.MergeSeparator[] mergeSeparators = body.getSpans(0, body.length(), Message.MergeSeparator.class);
528 for (Message.MergeSeparator mergeSeparator : mergeSeparators) {
529 int start = body.getSpanStart(mergeSeparator);
530 int end = body.getSpanEnd(mergeSeparator);
531 body.setSpan(new DividerSpan(true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
532 }
533 for (final android.text.style.QuoteSpan quote : body.getSpans(0, body.length(), android.text.style.QuoteSpan.class)) {
534 int start = body.getSpanStart(quote);
535 int end = body.getSpanEnd(quote);
536 body.removeSpan(quote);
537 applyQuoteSpan(body, start, end, darkBackground);
538 }
539 boolean startsWithQuote = handleTextQuotes(body, darkBackground);
540 if (!message.isPrivateMessage()) {
541 if (hasMeCommand) {
542 body.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, nick.length(),
543 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
544 }
545 } else {
546 String privateMarker;
547 if (message.getStatus() <= Message.STATUS_RECEIVED) {
548 privateMarker = activity.getString(R.string.private_message);
549 } else {
550 Jid cp = message.getCounterpart();
551 privateMarker = activity.getString(R.string.private_message_to, Strings.nullToEmpty(cp == null ? null : cp.getResource()));
552 }
553 body.insert(0, privateMarker);
554 int privateMarkerIndex = privateMarker.length();
555 if (startsWithQuote) {
556 body.insert(privateMarkerIndex, "\n\n");
557 body.setSpan(new DividerSpan(false), privateMarkerIndex, privateMarkerIndex + 2,
558 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
559 } else {
560 body.insert(privateMarkerIndex, " ");
561 }
562 body.setSpan(new ForegroundColorSpan(getMessageTextColor(darkBackground, false)), 0, privateMarkerIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
563 body.setSpan(new StyleSpan(Typeface.BOLD), 0, privateMarkerIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
564 if (hasMeCommand) {
565 body.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), privateMarkerIndex + 1,
566 privateMarkerIndex + 1 + nick.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
567 }
568 }
569 if (message.getConversation().getMode() == Conversation.MODE_MULTI && message.getStatus() == Message.STATUS_RECEIVED) {
570 if (message.getConversation() instanceof Conversation) {
571 final Conversation conversation = (Conversation) message.getConversation();
572 Pattern pattern = NotificationService.generateNickHighlightPattern(conversation.getMucOptions().getActualNick());
573 Matcher matcher = pattern.matcher(body);
574 while (matcher.find()) {
575 body.setSpan(new StyleSpan(Typeface.BOLD), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
576 }
577 }
578 }
579 Matcher matcher = Emoticons.getEmojiPattern(body).matcher(body);
580 while (matcher.find()) {
581 if (matcher.start() < matcher.end()) {
582 body.setSpan(new RelativeSizeSpan(1.2f), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
583 }
584 }
585
586 StylingHelper.format(body, viewHolder.messageBody.getCurrentTextColor());
587 if (highlightedTerm != null) {
588 StylingHelper.highlight(activity, body, highlightedTerm, StylingHelper.isDarkText(viewHolder.messageBody));
589 }
590 MyLinkify.addLinks(body, message.getConversation().getAccount(), message.getConversation().getJid());
591 viewHolder.messageBody.setAutoLinkMask(0);
592 viewHolder.messageBody.setText(body);
593 BetterLinkMovementMethod method = new BetterLinkMovementMethod() {
594 @Override
595 protected void dispatchUrlLongClick(TextView tv, ClickableSpan span) {
596 if (span instanceof URLSpan || mOnInlineImageLongClickedListener == null) {
597 super.dispatchUrlLongClick(tv, span);
598 return;
599 }
600
601 Spannable body = (Spannable) tv.getText();
602 ImageSpan[] imageSpans = body.getSpans(body.getSpanStart(span), body.getSpanEnd(span), ImageSpan.class);
603 if (imageSpans.length > 0) {
604 Uri uri = Uri.parse(imageSpans[0].getSource());
605 Cid cid = BobTransfer.cid(uri);
606 if (cid == null) return;
607 if (mOnInlineImageLongClickedListener.onInlineImageLongClicked(cid)) {
608 tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
609 }
610 }
611 }
612 };
613 method.setOnLinkLongClickListener((tv, url) -> {
614 tv.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
615 ShareUtil.copyLinkToClipboard(activity, url);
616 return true;
617 });
618 viewHolder.messageBody.setMovementMethod(method);
619 } else {
620 viewHolder.messageBody.setText("");
621 viewHolder.messageBody.setTextIsSelectable(false);
622 }
623 }
624
625 private void displayDownloadableMessage(ViewHolder viewHolder, final Message message, String text, final boolean darkBackground, final int type) {
626 displayTextMessage(viewHolder, message, darkBackground, type);
627 viewHolder.image.setVisibility(View.GONE);
628 List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
629 if (thumbs != null && !thumbs.isEmpty()) {
630 for (Element thumb : thumbs) {
631 Uri uri = Uri.parse(thumb.getAttribute("uri"));
632 if (uri.getScheme().equals("data")) {
633 String[] parts = uri.getSchemeSpecificPart().split(",", 2);
634 parts = parts[0].split(";");
635 if (!parts[0].equals("image/blurhash") && !parts[0].equals("image/jpeg") && !parts[0].equals("image/png") && !parts[0].equals("image/webp") && !parts[0].equals("image/gif")) continue;
636 } else if (uri.getScheme().equals("cid")) {
637 Cid cid = BobTransfer.cid(uri);
638 if (cid == null) continue;
639 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
640 if (f == null || !f.canRead()) {
641 if (!message.trusted() && !message.getConversation().canInferPresence()) continue;
642
643 try {
644 new BobTransfer(BobTransfer.uri(cid), message.getConversation().getAccount(), message.getCounterpart(), activity.xmppConnectionService).start();
645 } catch (final NoSuchAlgorithmException | URISyntaxException e) { }
646 continue;
647 }
648 } else {
649 continue;
650 }
651
652 int width = message.getFileParams().width;
653 if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
654 if (width < 1) width = 1920;
655
656 int height = message.getFileParams().height;
657 if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
658 if (height < 1) height = 1080;
659
660 viewHolder.image.setVisibility(View.VISIBLE);
661 imagePreviewLayout(width, height, viewHolder.image);
662 activity.loadBitmap(message, viewHolder.image);
663 viewHolder.image.setOnClickListener(v -> ConversationFragment.downloadFile(activity, message));
664
665 break;
666 }
667 }
668 viewHolder.audioPlayer.setVisibility(View.GONE);
669 viewHolder.download_button.setVisibility(View.VISIBLE);
670 viewHolder.download_button.setText(text);
671 viewHolder.download_button.setOnClickListener(v -> ConversationFragment.downloadFile(activity, message));
672 }
673
674 private void displayOpenableMessage(ViewHolder viewHolder, final Message message, final boolean darkBackground, final int type) {
675 displayTextMessage(viewHolder, message, darkBackground, type);
676 viewHolder.image.setVisibility(View.GONE);
677 viewHolder.audioPlayer.setVisibility(View.GONE);
678 viewHolder.download_button.setVisibility(View.VISIBLE);
679 viewHolder.download_button.setText(activity.getString(R.string.open_x_file, UIHelper.getFileDescriptionString(activity, message)));
680 viewHolder.download_button.setOnClickListener(v -> openDownloadable(message));
681 }
682
683 private void displayLocationMessage(ViewHolder viewHolder, final Message message, final boolean darkBackground, final int type) {
684 displayTextMessage(viewHolder, message, darkBackground, type);
685 viewHolder.image.setVisibility(View.GONE);
686 viewHolder.audioPlayer.setVisibility(View.GONE);
687 viewHolder.download_button.setVisibility(View.VISIBLE);
688 viewHolder.download_button.setText(R.string.show_location);
689 viewHolder.download_button.setOnClickListener(v -> showLocation(message));
690 }
691
692 private void displayAudioMessage(ViewHolder viewHolder, Message message, boolean darkBackground, final int type) {
693 displayTextMessage(viewHolder, message, darkBackground, type);
694 viewHolder.image.setVisibility(View.GONE);
695 viewHolder.download_button.setVisibility(View.GONE);
696 final RelativeLayout audioPlayer = viewHolder.audioPlayer;
697 audioPlayer.setVisibility(View.VISIBLE);
698 AudioPlayer.ViewHolder.get(audioPlayer).setDarkBackground(darkBackground);
699 this.audioPlayer.init(audioPlayer, message);
700 }
701
702 private void displayMediaPreviewMessage(ViewHolder viewHolder, final Message message, final boolean darkBackground, final int type) {
703 displayTextMessage(viewHolder, message, darkBackground, type);
704 viewHolder.download_button.setVisibility(View.GONE);
705 viewHolder.audioPlayer.setVisibility(View.GONE);
706 viewHolder.image.setVisibility(View.VISIBLE);
707 final FileParams params = message.getFileParams();
708 imagePreviewLayout(params.width, params.height, viewHolder.image);
709 activity.loadBitmap(message, viewHolder.image);
710 viewHolder.image.setOnClickListener(v -> openDownloadable(message));
711 }
712
713 private void imagePreviewLayout(int w, int h, ImageView image) {
714 final float target = activity.getResources().getDimension(R.dimen.image_preview_width);
715 final int scaledW;
716 final int scaledH;
717 if (Math.max(h, w) * metrics.density <= target) {
718 scaledW = (int) (w * metrics.density);
719 scaledH = (int) (h * metrics.density);
720 } else if (Math.max(h, w) <= target) {
721 scaledW = w;
722 scaledH = h;
723 } else if (w <= h) {
724 scaledW = (int) (w / ((double) h / target));
725 scaledH = (int) target;
726 } else {
727 scaledW = (int) target;
728 scaledH = (int) (h / ((double) w / target));
729 }
730 final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(scaledW, scaledH);
731 layoutParams.setMargins(0, (int) (metrics.density * 4), 0, (int) (metrics.density * 4));
732 image.setLayoutParams(layoutParams);
733 }
734
735 private void toggleWhisperInfo(ViewHolder viewHolder, final Message message, final boolean darkBackground) {
736 if (message.isPrivateMessage()) {
737 final String privateMarker;
738 if (message.getStatus() <= Message.STATUS_RECEIVED) {
739 privateMarker = activity.getString(R.string.private_message);
740 } else {
741 Jid cp = message.getCounterpart();
742 privateMarker = activity.getString(R.string.private_message_to, Strings.nullToEmpty(cp == null ? null : cp.getResource()));
743 }
744 final SpannableString body = new SpannableString(privateMarker);
745 body.setSpan(new ForegroundColorSpan(getMessageTextColor(darkBackground, false)), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
746 body.setSpan(new StyleSpan(Typeface.BOLD), 0, privateMarker.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
747 viewHolder.messageBody.setText(body);
748 viewHolder.messageBody.setVisibility(View.VISIBLE);
749 } else {
750 viewHolder.messageBody.setVisibility(View.GONE);
751 }
752 }
753
754 private void loadMoreMessages(Conversation conversation) {
755 conversation.setLastClearHistory(0, null);
756 activity.xmppConnectionService.updateConversation(conversation);
757 conversation.setHasMessagesLeftOnServer(true);
758 conversation.setFirstMamReference(null);
759 long timestamp = conversation.getLastMessageTransmitted().getTimestamp();
760 if (timestamp == 0) {
761 timestamp = System.currentTimeMillis();
762 }
763 conversation.messagesLoaded.set(true);
764 MessageArchiveService.Query query = activity.xmppConnectionService.getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
765 if (query != null) {
766 Toast.makeText(activity, R.string.fetching_history_from_server, Toast.LENGTH_LONG).show();
767 } else {
768 Toast.makeText(activity, R.string.not_fetching_history_retention_period, Toast.LENGTH_SHORT).show();
769 }
770 }
771
772 @Override
773 public View getView(int position, View view, ViewGroup parent) {
774 final Message message = getItem(position);
775 final boolean omemoEncryption = message.getEncryption() == Message.ENCRYPTION_AXOLOTL;
776 final boolean isInValidSession = message.isValidInSession() && (!omemoEncryption || message.isTrusted());
777 final Conversational conversation = message.getConversation();
778 final Account account = conversation.getAccount();
779 final List<Element> commands = message.getCommands();
780 final int type = getItemViewType(position);
781 ViewHolder viewHolder;
782 if (view == null) {
783 viewHolder = new ViewHolder();
784 switch (type) {
785 case DATE_SEPARATOR:
786 view = activity.getLayoutInflater().inflate(R.layout.message_date_bubble, parent, false);
787 viewHolder.status_message = view.findViewById(R.id.message_body);
788 viewHolder.message_box = view.findViewById(R.id.message_box);
789 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
790 break;
791 case RTP_SESSION:
792 view = activity.getLayoutInflater().inflate(R.layout.message_rtp_session, parent, false);
793 viewHolder.status_message = view.findViewById(R.id.message_body);
794 viewHolder.message_box = view.findViewById(R.id.message_box);
795 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
796 break;
797 case SENT:
798 view = activity.getLayoutInflater().inflate(R.layout.message_sent, parent, false);
799 viewHolder.message_box = view.findViewById(R.id.message_box);
800 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
801 viewHolder.download_button = view.findViewById(R.id.download_button);
802 viewHolder.indicator = view.findViewById(R.id.security_indicator);
803 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
804 viewHolder.image = view.findViewById(R.id.message_image);
805 viewHolder.messageBody = view.findViewById(R.id.message_body);
806 viewHolder.time = view.findViewById(R.id.message_time);
807 viewHolder.subject = view.findViewById(R.id.message_subject);
808 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
809 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
810 viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
811 break;
812 case RECEIVED:
813 view = activity.getLayoutInflater().inflate(R.layout.message_received, parent, false);
814 viewHolder.message_box = view.findViewById(R.id.message_box);
815 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
816 viewHolder.download_button = view.findViewById(R.id.download_button);
817 viewHolder.indicator = view.findViewById(R.id.security_indicator);
818 viewHolder.edit_indicator = view.findViewById(R.id.edit_indicator);
819 viewHolder.image = view.findViewById(R.id.message_image);
820 viewHolder.messageBody = view.findViewById(R.id.message_body);
821 viewHolder.time = view.findViewById(R.id.message_time);
822 viewHolder.subject = view.findViewById(R.id.message_subject);
823 viewHolder.indicatorReceived = view.findViewById(R.id.indicator_received);
824 viewHolder.encryption = view.findViewById(R.id.message_encryption);
825 viewHolder.audioPlayer = view.findViewById(R.id.audio_player);
826 viewHolder.commands_list = view.findViewById(R.id.commands_list);
827 viewHolder.thread_identicon = view.findViewById(R.id.thread_identicon);
828 break;
829 case STATUS:
830 view = activity.getLayoutInflater().inflate(R.layout.message_status, parent, false);
831 viewHolder.contact_picture = view.findViewById(R.id.message_photo);
832 viewHolder.status_message = view.findViewById(R.id.status_message);
833 viewHolder.load_more_messages = view.findViewById(R.id.load_more_messages);
834 break;
835 default:
836 throw new AssertionError("Unknown view type");
837 }
838 view.setTag(viewHolder);
839 } else {
840 viewHolder = (ViewHolder) view.getTag();
841 if (viewHolder == null) {
842 return view;
843 }
844 }
845
846 if (viewHolder.thread_identicon != null) {
847 viewHolder.thread_identicon.setVisibility(View.GONE);
848 final Element thread = message.getThread();
849 if (thread != null) {
850 final String threadId = thread.getContent();
851 if (threadId != null) {
852 viewHolder.thread_identicon.setVisibility(View.VISIBLE);
853 viewHolder.thread_identicon.setColor(UIHelper.getColorForName(threadId));
854 viewHolder.thread_identicon.setHash(UIHelper.identiconHash(threadId));
855 }
856 }
857 }
858
859 boolean darkBackground = type == RECEIVED && (!isInValidSession || mUseGreenBackground) || activity.isDarkTheme();
860
861 if (type == DATE_SEPARATOR) {
862 if (UIHelper.today(message.getTimeSent())) {
863 viewHolder.status_message.setText(R.string.today);
864 } else if (UIHelper.yesterday(message.getTimeSent())) {
865 viewHolder.status_message.setText(R.string.yesterday);
866 } else {
867 viewHolder.status_message.setText(DateUtils.formatDateTime(activity, message.getTimeSent(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
868 }
869 viewHolder.message_box.setBackgroundResource(activity.isDarkTheme() ? R.drawable.date_bubble_grey : R.drawable.date_bubble_white);
870 return view;
871 } else if (type == RTP_SESSION) {
872 final boolean isDarkTheme = activity.isDarkTheme();
873 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
874 final RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
875 final long duration = rtpSessionStatus.duration;
876 final String callTime = UIHelper.readableTimeDifferenceFull(activity, message.getTimeSent());
877 if (received) {
878 if (duration > 0) {
879 viewHolder.status_message.setText(activity.getString(R.string.incoming_call_duration_timestamp, TimeFrameUtils.resolve(activity, duration), callTime));
880 } else if (rtpSessionStatus.successful) {
881 viewHolder.status_message.setText(activity.getString(R.string.incoming_call_timestamp, callTime));
882 } else {
883 viewHolder.status_message.setText(activity.getString(R.string.missed_call_timestamp, callTime));
884 }
885 } else {
886 if (duration > 0) {
887 viewHolder.status_message.setText(activity.getString(R.string.outgoing_call_duration_timestamp, TimeFrameUtils.resolve(activity, duration), callTime));
888 } else {
889 viewHolder.status_message.setText(activity.getString(R.string.outgoing_call_timestamp, callTime));
890 }
891 }
892 viewHolder.indicatorReceived.setImageResource(RtpSessionStatus.getDrawable(received, rtpSessionStatus.successful, isDarkTheme));
893 viewHolder.indicatorReceived.setAlpha(isDarkTheme ? 0.7f : 0.57f);
894 viewHolder.message_box.setBackgroundResource(isDarkTheme ? R.drawable.date_bubble_grey : R.drawable.date_bubble_white);
895 return view;
896 } else if (type == STATUS) {
897 if ("LOAD_MORE".equals(message.getBody())) {
898 viewHolder.status_message.setVisibility(View.GONE);
899 viewHolder.contact_picture.setVisibility(View.GONE);
900 viewHolder.load_more_messages.setVisibility(View.VISIBLE);
901 viewHolder.load_more_messages.setOnClickListener(v -> loadMoreMessages((Conversation) message.getConversation()));
902 } else {
903 viewHolder.status_message.setVisibility(View.VISIBLE);
904 viewHolder.load_more_messages.setVisibility(View.GONE);
905 viewHolder.status_message.setText(message.getBody());
906 boolean showAvatar;
907 if (conversation.getMode() == Conversation.MODE_SINGLE) {
908 showAvatar = true;
909 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
910 } else if (message.getCounterpart() != null || message.getTrueCounterpart() != null || (message.getCounterparts() != null && message.getCounterparts().size() > 0)) {
911 showAvatar = true;
912 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar_on_status_message);
913 } else {
914 showAvatar = false;
915 }
916 if (showAvatar) {
917 viewHolder.contact_picture.setAlpha(0.5f);
918 viewHolder.contact_picture.setVisibility(View.VISIBLE);
919 } else {
920 viewHolder.contact_picture.setVisibility(View.GONE);
921 }
922 }
923 return view;
924 } else {
925 AvatarWorkerTask.loadAvatar(message, viewHolder.contact_picture, R.dimen.avatar);
926 }
927
928 resetClickListener(viewHolder.message_box, viewHolder.messageBody);
929
930 viewHolder.message_box.setOnClickListener(v -> {
931 if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
932 MessageAdapter.this.mOnMessageBoxClickedListener
933 .onContactPictureClicked(message);
934 }
935 });
936 SwipeDetector swipeDetector = new SwipeDetector((action) -> {
937 if (action == SwipeDetector.Action.LR && MessageAdapter.this.mOnMessageBoxSwipedListener != null) {
938 MessageAdapter.this.mOnMessageBoxSwipedListener.onContactPictureClicked(message);
939 }
940 });
941 viewHolder.message_box.setOnTouchListener(swipeDetector);
942 viewHolder.messageBody.setOnTouchListener(swipeDetector);
943 viewHolder.image.setOnTouchListener(swipeDetector);
944 viewHolder.time.setOnTouchListener(swipeDetector);
945 viewHolder.messageBody.setOnClickListener(v -> {
946 if (MessageAdapter.this.mOnMessageBoxClickedListener != null) {
947 MessageAdapter.this.mOnMessageBoxClickedListener
948 .onContactPictureClicked(message);
949 }
950 });
951 viewHolder.contact_picture.setOnClickListener(v -> {
952 if (MessageAdapter.this.mOnContactPictureClickedListener != null) {
953 MessageAdapter.this.mOnContactPictureClickedListener
954 .onContactPictureClicked(message);
955 }
956
957 });
958 viewHolder.contact_picture.setOnLongClickListener(v -> {
959 if (MessageAdapter.this.mOnContactPictureLongClickedListener != null) {
960 MessageAdapter.this.mOnContactPictureLongClickedListener
961 .onContactPictureLongClicked(v, message);
962 return true;
963 } else {
964 return false;
965 }
966 });
967
968 final Transferable transferable = message.getTransferable();
969 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(message);
970 if (unInitiatedButKnownSize || message.isDeleted() || (transferable != null && transferable.getStatus() != Transferable.STATUS_UPLOADING)) {
971 if (unInitiatedButKnownSize || transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER) {
972 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, message)), darkBackground, type);
973 } else if (transferable != null && transferable.getStatus() == Transferable.STATUS_OFFER_CHECK_FILESIZE) {
974 displayDownloadableMessage(viewHolder, message, activity.getString(R.string.check_x_filesize, UIHelper.getFileDescriptionString(activity, message)), darkBackground, type);
975 } else {
976 displayInfoMessage(viewHolder, UIHelper.getMessagePreview(activity, message).first, darkBackground, message, type);
977 }
978 } else if (message.isFileOrImage() && message.getEncryption() != Message.ENCRYPTION_PGP && message.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED) {
979 if (message.getFileParams().width > 0 && message.getFileParams().height > 0) {
980 displayMediaPreviewMessage(viewHolder, message, darkBackground, type);
981 } else if (message.getFileParams().runtime > 0) {
982 displayAudioMessage(viewHolder, message, darkBackground, type);
983 } else {
984 displayOpenableMessage(viewHolder, message, darkBackground, type);
985 }
986 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
987 if (account.isPgpDecryptionServiceConnected()) {
988 if (conversation instanceof Conversation && !account.hasPendingPgpIntent((Conversation) conversation)) {
989 displayInfoMessage(viewHolder, activity.getString(R.string.message_decrypting), darkBackground);
990 } else {
991 displayInfoMessage(viewHolder, activity.getString(R.string.pgp_message), darkBackground);
992 }
993 } else {
994 displayInfoMessage(viewHolder, activity.getString(R.string.install_openkeychain), darkBackground);
995 viewHolder.message_box.setOnClickListener(this::promptOpenKeychainInstall);
996 viewHolder.messageBody.setOnClickListener(this::promptOpenKeychainInstall);
997 }
998 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
999 displayInfoMessage(viewHolder, activity.getString(R.string.decryption_failed), darkBackground);
1000 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
1001 displayInfoMessage(viewHolder, activity.getString(R.string.not_encrypted_for_this_device), darkBackground);
1002 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1003 displayInfoMessage(viewHolder, activity.getString(R.string.omemo_decryption_failed), darkBackground);
1004 } else {
1005 if (message.isGeoUri()) {
1006 displayLocationMessage(viewHolder, message, darkBackground, type);
1007 } else if (message.treatAsDownloadable()) {
1008 try {
1009 final URI uri = message.getOob();
1010 displayDownloadableMessage(viewHolder,
1011 message,
1012 activity.getString(R.string.check_x_filesize_on_host,
1013 UIHelper.getFileDescriptionString(activity, message),
1014 uri.getHost()),
1015 darkBackground, type);
1016 } catch (Exception e) {
1017 displayDownloadableMessage(viewHolder,
1018 message,
1019 activity.getString(R.string.check_x_filesize,
1020 UIHelper.getFileDescriptionString(activity, message)),
1021 darkBackground, type);
1022 }
1023 } else if (message.bodyIsOnlyEmojis() && message.getType() != Message.TYPE_PRIVATE) {
1024 displayEmojiMessage(viewHolder, message.getBody().trim(), darkBackground);
1025 } else {
1026 displayTextMessage(viewHolder, message, darkBackground, type);
1027 }
1028 }
1029
1030 if (type == RECEIVED) {
1031 if (commands != null && conversation instanceof Conversation) {
1032 CommandButtonAdapter adapter = new CommandButtonAdapter(activity);
1033 adapter.addAll(commands);
1034 viewHolder.commands_list.setAdapter(adapter);
1035 viewHolder.commands_list.setVisibility(View.VISIBLE);
1036 viewHolder.commands_list.setOnItemClickListener((p, v, pos, id) -> {
1037 final Element command = adapter.getItem(pos);
1038 activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
1039 });
1040 } else {
1041 // It's unclear if we can set this to null...
1042 ListAdapter adapter = viewHolder.commands_list.getAdapter();
1043 if (adapter instanceof ArrayAdapter) {
1044 ((ArrayAdapter<?>) adapter).clear();
1045 }
1046 viewHolder.commands_list.setVisibility(View.GONE);
1047 viewHolder.commands_list.setOnItemClickListener(null);
1048 }
1049
1050 if (isInValidSession) {
1051 if (!mUseGreenBackground) {
1052 viewHolder.message_box.getBackground().setColorFilter(
1053 StyledAttributes.getColor(activity, mUseGreenBackground ? R.attr.message_bubble_received_bg : R.attr.color_background_primary),
1054 PorterDuff.Mode.SRC_ATOP
1055 );
1056 }
1057 viewHolder.encryption.setVisibility(View.GONE);
1058 } else {
1059 viewHolder.encryption.setVisibility(View.VISIBLE);
1060 if (omemoEncryption && !message.isTrusted()) {
1061 viewHolder.encryption.setText(R.string.not_trusted);
1062 } else {
1063 viewHolder.encryption.setText(CryptoHelper.encryptionTypeToText(message.getEncryption()));
1064 }
1065 }
1066 }
1067
1068 if (type == RECEIVED || type == SENT) {
1069 if (message.getSubject() == null) {
1070 viewHolder.subject.setVisibility(View.GONE);
1071 } else {
1072 viewHolder.subject.setVisibility(View.VISIBLE);
1073 viewHolder.subject.setText(message.getSubject());
1074 }
1075 }
1076
1077 displayStatus(viewHolder, message, type, darkBackground);
1078
1079 return view;
1080 }
1081
1082 private void promptOpenKeychainInstall(View view) {
1083 activity.showInstallPgpDialog();
1084 }
1085
1086 public FileBackend getFileBackend() {
1087 return activity.xmppConnectionService.getFileBackend();
1088 }
1089
1090 public void stopAudioPlayer() {
1091 audioPlayer.stop();
1092 }
1093
1094 public void unregisterListenerInAudioPlayer() {
1095 audioPlayer.unregisterListener();
1096 }
1097
1098 public void startStopPending() {
1099 audioPlayer.startStopPending();
1100 }
1101
1102 public void openDownloadable(Message message) {
1103 if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1104 ConversationFragment.registerPendingMessage(activity, message);
1105 ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ConversationsActivity.REQUEST_OPEN_MESSAGE);
1106 return;
1107 }
1108 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1109 ViewUtil.view(activity, file);
1110 }
1111
1112 private void showLocation(Message message) {
1113 for (Intent intent : GeoHelper.createGeoIntentsFromMessage(activity, message)) {
1114 if (intent.resolveActivity(getContext().getPackageManager()) != null) {
1115 getContext().startActivity(intent);
1116 return;
1117 }
1118 }
1119 Toast.makeText(activity, R.string.no_application_found_to_display_location, Toast.LENGTH_SHORT).show();
1120 }
1121
1122 public void updatePreferences() {
1123 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1124 this.mUseGreenBackground = p.getBoolean("use_green_background", activity.getResources().getBoolean(R.bool.use_green_background));
1125 }
1126
1127
1128 public void setHighlightedTerm(List<String> terms) {
1129 this.highlightedTerm = terms == null ? null : StylingHelper.filterHighlightedWords(terms);
1130 }
1131
1132 public interface OnContactPictureClicked {
1133 void onContactPictureClicked(Message message);
1134 }
1135
1136 public interface OnContactPictureLongClicked {
1137 void onContactPictureLongClicked(View v, Message message);
1138 }
1139
1140 public interface OnInlineImageLongClicked {
1141 boolean onInlineImageLongClicked(Cid cid);
1142 }
1143
1144 private static class ViewHolder {
1145
1146 public Button load_more_messages;
1147 public ImageView edit_indicator;
1148 public RelativeLayout audioPlayer;
1149 protected LinearLayout message_box;
1150 protected Button download_button;
1151 protected ImageView image;
1152 protected ImageView indicator;
1153 protected ImageView indicatorReceived;
1154 protected TextView time;
1155 protected TextView subject;
1156 protected TextView messageBody;
1157 protected ImageView contact_picture;
1158 protected TextView status_message;
1159 protected TextView encryption;
1160 protected ListView commands_list;
1161 protected GithubIdenticonView thread_identicon;
1162 }
1163
1164 class ThumbnailTask extends AsyncTask<DownloadableFile, Void, Drawable[]> {
1165 @Override
1166 protected Drawable[] doInBackground(DownloadableFile... params) {
1167 if (isCancelled()) return null;
1168
1169 Drawable[] d = new Drawable[params.length];
1170 for (int i = 0; i < params.length; i++) {
1171 try {
1172 d[i] = activity.xmppConnectionService.getFileBackend().getThumbnail(params[i], activity.getResources(), (int) (metrics.density * 288), false);
1173 } catch (final IOException e) {
1174 d[i] = null;
1175 }
1176 }
1177
1178 return d;
1179 }
1180
1181 @Override
1182 protected void onPostExecute(final Drawable[] d) {
1183 if (isCancelled()) return;
1184 activity.xmppConnectionService.updateConversationUi();
1185 }
1186 }
1187}