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