MessageAdapter.java

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