UIHelper.java

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