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