UIHelper.java

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