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