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