UIHelper.java

  1package eu.siacs.conversations.utils;
  2
  3import android.content.Context;
  4import android.graphics.drawable.Drawable;
  5import android.content.res.ColorStateList;
  6import android.text.SpannableStringBuilder;
  7import android.text.format.DateFormat;
  8import android.text.format.DateUtils;
  9import android.util.Pair;
 10import android.widget.TextView;
 11
 12import androidx.annotation.ColorInt;
 13import androidx.core.content.res.ResourcesCompat;
 14import androidx.annotation.ColorRes;
 15import androidx.annotation.StringRes;
 16import androidx.core.content.ContextCompat;
 17
 18import com.google.android.material.color.MaterialColors;
 19import com.google.common.base.Strings;
 20import com.google.common.primitives.Ints;
 21
 22import java.math.BigInteger;
 23import java.nio.charset.StandardCharsets;
 24import java.security.MessageDigest;
 25import java.util.Arrays;
 26import java.util.Calendar;
 27import java.util.Date;
 28import java.util.List;
 29import java.util.Locale;
 30
 31import eu.siacs.conversations.Config;
 32import eu.siacs.conversations.R;
 33import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 34import eu.siacs.conversations.entities.Account;
 35import eu.siacs.conversations.entities.Contact;
 36import eu.siacs.conversations.entities.Conversation;
 37import eu.siacs.conversations.entities.Conversational;
 38import eu.siacs.conversations.entities.ListItem;
 39import eu.siacs.conversations.entities.Message;
 40import eu.siacs.conversations.entities.MucOptions;
 41import eu.siacs.conversations.entities.Presence;
 42import eu.siacs.conversations.entities.RtpSessionStatus;
 43import eu.siacs.conversations.entities.Transferable;
 44import eu.siacs.conversations.services.ExportBackupService;
 45import eu.siacs.conversations.services.XmppConnectionService;
 46import eu.siacs.conversations.ui.util.MyLinkify;
 47import eu.siacs.conversations.ui.util.QuoteHelper;
 48import eu.siacs.conversations.xmpp.Jid;
 49
 50public class UIHelper {
 51
 52    private static final List<String> LOCATION_QUESTIONS = Arrays.asList(
 53            "where are you", //en
 54            "where are you now", //en
 55            "where are you right now", //en
 56            "whats your 20", //en
 57            "what is your 20", //en
 58            "what's your 20", //en
 59            "whats your twenty", //en
 60            "what is your twenty", //en
 61            "what's your twenty", //en
 62            "wo bist du", //de
 63            "wo bist du jetzt", //de
 64            "wo bist du gerade", //de
 65            "wo seid ihr", //de
 66            "wo seid ihr jetzt", //de
 67            "wo seid ihr gerade", //de
 68            "dónde estás", //es
 69            "donde estas" //es
 70    );
 71
 72    private static final List<Character> PUNCTIONATION = Arrays.asList('.', ',', '?', '!', ';', ':');
 73
 74    private static final int SHORT_DATE_FLAGS = DateUtils.FORMAT_SHOW_DATE
 75            | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
 76    private static final int FULL_DATE_FLAGS = DateUtils.FORMAT_SHOW_TIME
 77            | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE;
 78
 79    public static String readableTimeDifference(Context context, long time) {
 80        return readableTimeDifference(context, time, false);
 81    }
 82
 83    public static String readableTimeDifferenceFull(Context context, long time) {
 84        return readableTimeDifference(context, time, true);
 85    }
 86
 87    private static String readableTimeDifference(Context context, long time,
 88                                                 boolean fullDate) {
 89        if (time == 0) {
 90            return context.getString(R.string.just_now);
 91        }
 92        Date date = new Date(time);
 93        long difference = (System.currentTimeMillis() - time) / 1000;
 94        if (difference < 60) {
 95            return context.getString(R.string.just_now);
 96        } else if (difference < 60 * 2) {
 97            return context.getString(R.string.minute_ago);
 98        } else if (difference < 60 * 15) {
 99            return context.getString(R.string.minutes_ago, Math.round(difference / 60.0));
100        } else if (today(date)) {
101            java.text.DateFormat df = DateFormat.getTimeFormat(context);
102            return df.format(date);
103        } else {
104            if (fullDate) {
105                return DateUtils.formatDateTime(context, date.getTime(),
106                        FULL_DATE_FLAGS);
107            } else {
108                return DateUtils.formatDateTime(context, date.getTime(),
109                        SHORT_DATE_FLAGS);
110            }
111        }
112    }
113
114    private static boolean today(Date date) {
115        return sameDay(date, new Date(System.currentTimeMillis()));
116    }
117
118    public static boolean today(long date) {
119        return sameDay(date, System.currentTimeMillis());
120    }
121
122    public static boolean yesterday(long date) {
123        Calendar cal1 = Calendar.getInstance();
124        Calendar cal2 = Calendar.getInstance();
125        cal1.add(Calendar.DAY_OF_YEAR, -1);
126        cal2.setTime(new Date(date));
127        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
128                && cal1.get(Calendar.DAY_OF_YEAR) == cal2
129                .get(Calendar.DAY_OF_YEAR);
130    }
131
132    public static boolean sameDay(long a, long b) {
133        return sameDay(new Date(a), new Date(b));
134    }
135
136    private static boolean sameDay(Date a, Date b) {
137        Calendar cal1 = Calendar.getInstance();
138        Calendar cal2 = Calendar.getInstance();
139        cal1.setTime(a);
140        cal2.setTime(b);
141        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
142                && cal1.get(Calendar.DAY_OF_YEAR) == cal2
143                .get(Calendar.DAY_OF_YEAR);
144    }
145
146    public static String lastseen(Context context, boolean active, long time) {
147        long difference = (System.currentTimeMillis() - time) / 1000;
148        if (active) {
149            return context.getString(R.string.online_right_now);
150        } else if (difference < 60) {
151            return context.getString(R.string.last_seen_now);
152        } else if (difference < 60 * 2) {
153            return context.getString(R.string.last_seen_min);
154        } else if (difference < 60 * 60) {
155            return context.getString(R.string.last_seen_mins, Math.round(difference / 60.0));
156        } else if (difference < 60 * 60 * 2) {
157            return context.getString(R.string.last_seen_hour);
158        } else if (difference < 60 * 60 * 24) {
159            return context.getString(R.string.last_seen_hours,
160                    Math.round(difference / (60.0 * 60.0)));
161        } else if (difference < 60 * 60 * 48) {
162            return context.getString(R.string.last_seen_day);
163        } else {
164            return context.getString(R.string.last_seen_days,
165                    Math.round(difference / (60.0 * 60.0 * 24.0)));
166        }
167    }
168
169    public static int identiconHash(String name) {
170        try {
171            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
172            byte[] digest = sha1.digest(name.getBytes(StandardCharsets.UTF_8));
173            return Ints.fromByteArray(digest);
174        } catch (Exception e) {
175            return 0;
176        }
177    }
178
179    public static int getColorForName(String name) {
180        return XEP0392Helper.rgbFromNick(name);
181    }
182
183    public static Pair<CharSequence, Boolean> getMessagePreview(final XmppConnectionService context, final Message message) {
184        return getMessagePreview(context, message, 0);
185    }
186
187    public static Pair<CharSequence, Boolean> getMessagePreview(final XmppConnectionService context, final Message message, @ColorInt int textColor) {
188        final Transferable d = message.getTransferable();
189        final boolean moderated = message.getModerated() != null;
190        final boolean muted = message.getStatus() == Message.STATUS_RECEIVED && message.getConversation().getMode() == Conversation.MODE_MULTI && context.isMucUserMuted(new MucOptions.User(null, message.getConversation().getJid(), message.getOccupantId(), null, null));
191        if (muted) {
192            return new Pair<>("Muted", false);
193        } else if (d != null && !moderated) {
194            switch (d.getStatus()) {
195                case Transferable.STATUS_CHECKING:
196                    return new Pair<>(context.getString(R.string.checking_x,
197                            getFileDescriptionString(context, message)), true);
198                case Transferable.STATUS_DOWNLOADING:
199                    return new Pair<>(context.getString(R.string.receiving_x_file,
200                            getFileDescriptionString(context, message),
201                            d.getProgress()), true);
202                case Transferable.STATUS_OFFER:
203                case Transferable.STATUS_OFFER_CHECK_FILESIZE:
204                    return new Pair<>(context.getString(R.string.x_file_offered_for_download,
205                            getFileDescriptionString(context, message)), true);
206                case Transferable.STATUS_FAILED:
207                    return new Pair<>(context.getString(R.string.file_transmission_failed), true);
208                case Transferable.STATUS_CANCELLED:
209                    return new Pair<>(context.getString(R.string.file_transmission_cancelled), true);
210                case Transferable.STATUS_UPLOADING:
211                    if (message.getStatus() == Message.STATUS_OFFERED) {
212                        return new Pair<>(context.getString(R.string.offering_x_file,
213                                getFileDescriptionString(context, message)), true);
214                    } else {
215                        return new Pair<>(context.getString(R.string.sending_x_file,
216                                getFileDescriptionString(context, message)), true);
217                    }
218                default:
219                    return new Pair<>("", false);
220            }
221        } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
222            return new Pair<>(context.getString(R.string.pgp_message), true);
223        } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
224            return new Pair<>(context.getString(R.string.decryption_failed), true);
225        } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
226            return new Pair<>(context.getString(R.string.not_encrypted_for_this_device), true);
227        } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
228            return new Pair<>(context.getString(R.string.omemo_decryption_failed), true);
229        } else if (message.isFileOrImage() && !moderated) {
230            return new Pair<>(getFileDescriptionString(context, message), true);
231        } else if (message.getType() == Message.TYPE_RTP_SESSION) {
232            RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
233            final boolean received = message.getStatus() == Message.STATUS_RECEIVED;
234            if (!rtpSessionStatus.successful && received) {
235                return new Pair<>(context.getString(R.string.missed_call), true);
236            } else {
237                return new Pair<>(context.getString(received ? R.string.incoming_call : R.string.outgoing_call), true);
238            }
239        } else {
240            final String body = MessageUtils.filterLtrRtl(message.getBody());
241            if (body.startsWith(Message.ME_COMMAND)) {
242                return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
243                        UIHelper.getMessageDisplayName(message) + " "), false);
244            } else if (message.isGeoUri()) {
245                return new Pair<>(context.getString(R.string.location), true);
246            } else if (!moderated && (message.treatAsDownloadable() || MessageUtils.unInitiatedButKnownSize(message))) {
247                return new Pair<>(context.getString(R.string.x_file_offered_for_download,
248                        getFileDescriptionString(context, message)), true);
249            } else {
250                Drawable fallbackImg = ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_photo_24dp, null);
251                fallbackImg.setBounds(0, 0, fallbackImg.getIntrinsicWidth(), fallbackImg.getIntrinsicHeight());
252                SpannableStringBuilder styledBody = message.getSpannableBody(null, fallbackImg);
253                if (textColor != 0) {
254                    StylingHelper.format(styledBody, 0, styledBody.length() - 1, textColor);
255                }
256                MyLinkify.addLinks(styledBody, message.getConversation().getAccount(), message.getConversation().getJid());
257                SpannableStringBuilder builder = new SpannableStringBuilder();
258                for (CharSequence l : CharSequenceUtils.split(styledBody, '\n')) {
259                    if (l.length() > 0) {
260                        if (l.toString().equals("```")) {
261                            continue;
262                        }
263                        char first = l.charAt(0);
264                        if ((!QuoteHelper.isPositionQuoteStart(l, 0))) {
265                            CharSequence line = CharSequenceUtils.trim(l);
266                            if (line.length() == 0) {
267                                continue;
268                            }
269                            char last = line.charAt(line.length() - 1);
270                            if (builder.length() != 0) {
271                                builder.append(' ');
272                            }
273                            builder.append(line);
274                            if (!PUNCTIONATION.contains(last)) {
275                                break;
276                            }
277                        }
278                    }
279                }
280                if (builder.length() == 0) {
281                    builder.append(body.trim());
282                }
283                return new Pair<>(builder, false);
284            }
285        }
286    }
287
288    public static boolean isLastLineQuote(String body) {
289        if (body.endsWith("\n")) {
290            return false;
291        }
292        String[] lines = body.split("\n");
293        if (lines.length == 0) {
294            return false;
295        }
296        String line = lines[lines.length - 1];
297        if (line.isEmpty()) {
298            return false;
299        }
300        char first = line.charAt(0);
301        return first == '>' && isPositionFollowedByQuoteableCharacter(line, 0) || first == '\u00bb';
302    }
303
304    public static CharSequence shorten(CharSequence input) {
305        return input.length() > 256 ? StylingHelper.subSequence(input, 0, 256) : input;
306    }
307
308    public static boolean isPositionPrecededByBodyStart(CharSequence body, int pos){
309        // true if not a single linebreak before current position
310        for (int i = pos - 1; i >= 0; i--){
311            if (body.charAt(i) != ' '){
312                return false;
313            }
314        }
315        return true;
316    }
317
318    public static boolean isPositionPrecededByLineStart(CharSequence body, int pos){
319        if (isPositionPrecededByBodyStart(body, pos)){
320            return true;
321        }
322        return body.charAt(pos - 1) == '\n';
323    }
324
325    public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
326        return !isPositionFollowedByNumber(body, pos)
327                && !isPositionFollowedByEmoticon(body, pos)
328                && !isPositionFollowedByEquals(body, pos);
329    }
330
331    private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
332        boolean previousWasNumber = false;
333        for (int i = pos + 1; i < body.length(); i++) {
334            char c = body.charAt(i);
335            if (Character.isDigit(body.charAt(i))) {
336                previousWasNumber = true;
337            } else if (previousWasNumber && (c == '.' || c == ',')) {
338                previousWasNumber = false;
339            } else {
340                return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
341            }
342        }
343        return previousWasNumber;
344    }
345
346    private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
347        return body.length() > pos + 1 && body.charAt(pos + 1) == '=';
348    }
349
350    private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
351        if (body.length() <= pos + 1) {
352            return false;
353        } else {
354            final char first = body.charAt(pos + 1);
355            return first == ';'
356                    || first == ':'
357                    || first == '.' // do not quote >.< (but >>.<)
358                    || closingBeforeWhitespace(body, pos + 1);
359        }
360    }
361
362    private static boolean closingBeforeWhitespace(CharSequence body, int pos) {
363        for (int i = pos; i < body.length(); ++i) {
364            final char c = body.charAt(i);
365            if (Character.isWhitespace(c)) {
366                return false;
367            } else if (QuoteHelper.isPositionQuoteCharacter(body, pos) || QuoteHelper.isPositionQuoteEndCharacter(body, pos)) {
368                return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
369            }
370        }
371        return false;
372    }
373
374    public static String getDisplayName(MucOptions.User user) {
375        Contact contact = user.getContact();
376        if (contact != null) {
377            return contact.getDisplayName();
378        } else {
379            final String name = user.getNick();
380            if (name != null) {
381                return name;
382            }
383            final Jid realJid = user.getRealJid();
384            if (realJid != null) {
385                return JidHelper.localPartOrFallback(realJid);
386            }
387            return null;
388        }
389    }
390
391    public static String concatNames(List<MucOptions.User> users) {
392        return concatNames(users, users.size());
393    }
394
395    public static String concatNames(List<MucOptions.User> users, int max) {
396        StringBuilder builder = new StringBuilder();
397        final boolean shortNames = users.size() >= 3;
398        for (int i = 0; i < Math.min(users.size(), max); ++i) {
399            if (builder.length() != 0) {
400                builder.append(", ");
401            }
402            final String name = UIHelper.getDisplayName(users.get(i));
403            if (name != null) {
404                builder.append(shortNames ? name.split("\\s+")[0] : name);
405            }
406        }
407        return builder.toString();
408    }
409
410    public static String getFileDescriptionString(final Context context, final Message message) {
411        final String mime = message.getMimeType();
412        if (Strings.isNullOrEmpty(mime)) {
413            return context.getString(R.string.file);
414        } else if (MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime)) {
415            return context.getString(R.string.multimedia_file);
416        } else if (mime.equals("audio/x-m4b")) {
417            return context.getString(R.string.audiobook);
418        } else if (mime.startsWith("audio/")) {
419            return context.getString(R.string.audio);
420        } else if (mime.startsWith("video/")) {
421            return context.getString(R.string.video);
422        } else if (mime.equals("image/gif")) {
423            return context.getString(R.string.gif);
424        } else if (mime.equals("image/svg+xml")) {
425            return context.getString(R.string.vector_graphic);
426        } else if (mime.startsWith("image/") || message.getType() == Message.TYPE_IMAGE) {
427            return context.getString(R.string.image);
428        } else if (mime.contains("pdf")) {
429            return context.getString(R.string.pdf_document);
430        } else if (mime.equals("application/vnd.android.package-archive")) {
431            return context.getString(R.string.apk);
432        } else if (mime.equals(ExportBackupService.MIME_TYPE)) {
433            return context.getString(R.string.conversations_backup);
434        } else if (mime.contains("vcard")) {
435            return context.getString(R.string.vcard);
436        } else if (mime.equals("text/x-vcalendar") || mime.equals("text/calendar")) {
437            return context.getString(R.string.event);
438        } else if (mime.equals("application/epub+zip") || mime.equals("application/vnd.amazon.mobi8-ebook")) {
439            return context.getString(R.string.ebook);
440        } else if (mime.equals("application/gpx+xml")) {
441            return context.getString(R.string.gpx_track);
442        } else if (mime.equals("application/xdc+zip")) {
443            return "Widget";
444        } else if (mime.equals("text/plain")) {
445            return context.getString(R.string.plain_text_document);
446        } else {
447            return mime;
448        }
449    }
450
451    public static String getMessageDisplayName(final Message message) {
452        if (message.getModerated() != null) return "moderated";
453
454        final Conversational conversation = message.getConversation();
455        if (message.getStatus() == Message.STATUS_RECEIVED) {
456            final Contact contact = message.getContact();
457            if (conversation.getMode() == Conversation.MODE_MULTI) {
458                if (contact != null) {
459                    return contact.getDisplayName();
460                } else {
461                    if (conversation instanceof Conversation) {
462                        final MucOptions.User user = ((Conversation) conversation).getMucOptions().findUserByFullJid(message.getCounterpart());
463                        if (user != null) {
464                            final String dname = getDisplayName(user);
465                            if (dname != null) return dname;
466                        }
467                    }
468                    return getDisplayedMucCounterpart(message.getCounterpart());
469                }
470            } else {
471                return contact != null ? contact.getDisplayName() : "";
472            }
473        } else {
474            if (conversation instanceof Conversation && conversation.getMode() == Conversation.MODE_MULTI) {
475                return ((Conversation) conversation).getMucOptions().getSelf().getNick();
476            } else {
477                final Account account = conversation.getAccount();
478                final Jid jid = account.getJid();
479                final String displayName = account.getDisplayName();
480                if (Strings.isNullOrEmpty(displayName)) {
481                    return jid.getLocal() != null ? jid.getLocal() : jid.getDomain().toString();
482                } else {
483                    return displayName;
484                }
485
486            }
487        }
488    }
489
490    public static String getMessageHint(final Context context,final  Conversation conversation) {
491        return switch (conversation.getNextEncryption()) {
492            case Message.ENCRYPTION_NONE -> {
493                if (Config.multipleEncryptionChoices()) {
494                    yield context.getString(R.string.send_message);
495                } else {
496                    yield context.getString(R.string.send_message_to_x, conversation.getName());
497                }
498            }
499            case Message.ENCRYPTION_AXOLOTL -> {
500                final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
501                if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
502                    yield context.getString(R.string.send_omemo_x509_message);
503                } else {
504                    yield context.getString(R.string.send_encrypted_message);
505                }
506            }
507            default -> context.getString(R.string.send_encrypted_message);
508        };
509    }
510
511    public static String getDisplayedMucCounterpart(final Jid counterpart) {
512        if (counterpart == null) {
513            return "";
514        } else if (!counterpart.isBareJid()) {
515            return counterpart.getResource().trim();
516        } else {
517            return counterpart.toString().trim();
518        }
519    }
520
521    public static boolean receivedLocationQuestion(final Message message) {
522        if (message == null
523                || message.getStatus() != Message.STATUS_RECEIVED
524                || message.getType() != Message.TYPE_TEXT) {
525            return false;
526        }
527        final String body = Strings.nullToEmpty(message.getBody())
528                .trim()
529                .toLowerCase(Locale.getDefault())
530                .replace("?", "").replace("¿", "");
531        return LOCATION_QUESTIONS.contains(body);
532    }
533
534    public static void setStatus(final TextView textView, Presence.Status status) {
535        final @StringRes int text;
536        final @ColorRes int color =
537                switch (status) {
538                    case CHAT -> {
539                        text = R.string.presence_chat;
540                        yield R.color.green_800;
541                    }
542                    case ONLINE -> {
543                        text = R.string.presence_online;
544                        yield R.color.green_800;
545                    }
546                    case AWAY -> {
547                        text = R.string.presence_away;
548                        yield R.color.amber_800;
549                    }
550                    case XA -> {
551                        text = R.string.presence_xa;
552                        yield R.color.orange_800;
553                    }
554                    case DND -> {
555                        text = R.string.presence_dnd;
556                        yield R.color.red_800;
557                    }
558                    default -> throw new IllegalStateException();
559                };
560        textView.setText(text);
561        textView.setBackgroundTintList(
562                ColorStateList.valueOf(
563                        MaterialColors.harmonizeWithPrimary(
564                                textView.getContext(),
565                                ContextCompat.getColor(textView.getContext(), color))));
566    }
567
568    public static String filesizeToString(long size) {
569        if (size > (1.5 * 1024 * 1024)) {
570            return Math.round(size * 1f / (1024 * 1024)) + " MiB";
571        } else if (size >= 1024) {
572            return Math.round(size * 1f / 1024) + " KiB";
573        } else {
574            return size + " B";
575        }
576    }
577}