UIHelper.java

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