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