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 if (start == 0 && end == styledBody.length()) continue;
263 styledBody.delete(start, end);
264 styledBody.removeSpan(quote);
265 }
266 if (!processMarkup) return new Pair<>(styledBody, false);
267
268 SpannableStringBuilder builder = new SpannableStringBuilder();
269 for (CharSequence l : CharSequenceUtils.split(styledBody, '\n')) {
270 if (l.length() > 0) {
271 if (l.toString().equals("```")) {
272 continue;
273 }
274 char first = l.charAt(0);
275 if ((!QuoteHelper.isPositionQuoteStart(l, 0))) {
276 CharSequence line = CharSequenceUtils.trim(l);
277 if (line.length() == 0) {
278 continue;
279 }
280 char last = line.charAt(line.length() - 1);
281 if (builder.length() != 0) {
282 builder.append(' ');
283 }
284 builder.append(line);
285 if (!PUNCTIONATION.contains(last)) {
286 break;
287 }
288 }
289 }
290 }
291 if (builder.length() == 0) {
292 builder.append(body.trim());
293 }
294 return new Pair<>(builder, false);
295 }
296 }
297 }
298
299 public static boolean isLastLineQuote(String body) {
300 if (body.endsWith("\n")) {
301 return false;
302 }
303 String[] lines = body.split("\n");
304 if (lines.length == 0) {
305 return false;
306 }
307 String line = lines[lines.length - 1];
308 if (line.isEmpty()) {
309 return false;
310 }
311 char first = line.charAt(0);
312 return first == '>' && isPositionFollowedByQuoteableCharacter(line, 0) || first == '\u00bb';
313 }
314
315 public static CharSequence shorten(CharSequence input) {
316 return input.length() > 256 ? StylingHelper.subSequence(input, 0, 256) : input;
317 }
318
319 public static boolean isPositionPrecededByBodyStart(CharSequence body, int pos){
320 // true if not a single linebreak before current position
321 for (int i = pos - 1; i >= 0; i--){
322 if (body.charAt(i) != ' '){
323 return false;
324 }
325 }
326 return true;
327 }
328
329 public static boolean isPositionPrecededByLineStart(CharSequence body, int pos){
330 if (isPositionPrecededByBodyStart(body, pos)){
331 return true;
332 }
333 return body.charAt(pos - 1) == '\n';
334 }
335
336 public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
337 return !isPositionFollowedByNumber(body, pos)
338 && !isPositionFollowedByEmoticon(body, pos)
339 && !isPositionFollowedByEquals(body, pos);
340 }
341
342 private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
343 boolean previousWasNumber = false;
344 for (int i = pos + 1; i < body.length(); i++) {
345 char c = body.charAt(i);
346 if (Character.isDigit(body.charAt(i))) {
347 previousWasNumber = true;
348 } else if (previousWasNumber && (c == '.' || c == ',')) {
349 previousWasNumber = false;
350 } else {
351 return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
352 }
353 }
354 return previousWasNumber;
355 }
356
357 private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
358 return body.length() > pos + 1 && body.charAt(pos + 1) == '=';
359 }
360
361 private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
362 if (body.length() <= pos + 1) {
363 return false;
364 } else {
365 final char first = body.charAt(pos + 1);
366 return first == ';'
367 || first == ':'
368 || first == '.' // do not quote >.< (but >>.<)
369 || closingBeforeWhitespace(body, pos + 1);
370 }
371 }
372
373 private static boolean closingBeforeWhitespace(CharSequence body, int pos) {
374 for (int i = pos; i < body.length(); ++i) {
375 final char c = body.charAt(i);
376 if (Character.isWhitespace(c)) {
377 return false;
378 } else if (QuoteHelper.isPositionQuoteCharacter(body, pos) || QuoteHelper.isPositionQuoteEndCharacter(body, pos)) {
379 return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
380 }
381 }
382 return false;
383 }
384
385 public static String getDisplayName(MucOptions.User user) {
386 Contact contact = user.getContact();
387 if (contact != null) {
388 return contact.getDisplayName();
389 } else {
390 final String name = user.getNick();
391 if (name != null) {
392 return name;
393 }
394 final Jid realJid = user.getRealJid();
395 if (realJid != null) {
396 return JidHelper.localPartOrFallback(realJid);
397 }
398 return null;
399 }
400 }
401
402 public static String concatNames(List<MucOptions.User> users) {
403 return concatNames(users, users.size());
404 }
405
406 public static String concatNames(List<MucOptions.User> users, int max) {
407 StringBuilder builder = new StringBuilder();
408 final boolean shortNames = users.size() >= 3;
409 for (int i = 0; i < Math.min(users.size(), max); ++i) {
410 if (builder.length() != 0) {
411 builder.append(", ");
412 }
413 final String name = UIHelper.getDisplayName(users.get(i));
414 if (name != null) {
415 builder.append(shortNames ? name.split("\\s+")[0] : name);
416 }
417 }
418 return builder.toString();
419 }
420
421 public static String getFileDescriptionString(final Context context, final Message message) {
422 final String mime = message.getMimeType();
423 if (Strings.isNullOrEmpty(mime)) {
424 return context.getString(R.string.file);
425 } else if (MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime)) {
426 return context.getString(R.string.multimedia_file);
427 } else if (mime.equals("audio/x-m4b")) {
428 return context.getString(R.string.audiobook);
429 } else if (mime.startsWith("audio/")) {
430 return context.getString(R.string.audio);
431 } else if (mime.startsWith("video/")) {
432 return context.getString(R.string.video);
433 } else if (mime.equals("image/gif")) {
434 return context.getString(R.string.gif);
435 } else if (mime.equals("image/svg+xml")) {
436 return context.getString(R.string.vector_graphic);
437 } else if (mime.startsWith("image/") || message.getType() == Message.TYPE_IMAGE) {
438 return context.getString(R.string.image);
439 } else if (mime.contains("pdf")) {
440 return context.getString(R.string.pdf_document);
441 } else if (mime.equals("application/vnd.android.package-archive")) {
442 return context.getString(R.string.apk);
443 } else if (mime.equals(ExportBackupWorker.MIME_TYPE)) {
444 return context.getString(R.string.conversations_backup);
445 } else if (mime.contains("vcard")) {
446 return context.getString(R.string.vcard);
447 } else if (mime.equals("text/x-vcalendar") || mime.equals("text/calendar")) {
448 return context.getString(R.string.event);
449 } else if (mime.equals("application/epub+zip") || mime.equals("application/vnd.amazon.mobi8-ebook")) {
450 return context.getString(R.string.ebook);
451 } else if (mime.equals("application/gpx+xml")) {
452 return context.getString(R.string.gpx_track);
453 } else if (mime.equals("application/xdc+zip")) {
454 return "Widget";
455 } else if (mime.equals("text/plain")) {
456 return context.getString(R.string.plain_text_document);
457 } else {
458 return mime;
459 }
460 }
461
462 public static String getMessageDisplayName(final Message message) {
463 if (message.getModerated() != null) return "moderated";
464
465 final Conversational conversation = message.getConversation();
466 if (message.getStatus() == Message.STATUS_RECEIVED) {
467 final Contact contact = message.getContact();
468 if (conversation.getMode() == Conversation.MODE_MULTI) {
469 if (contact != null) {
470 return contact.getDisplayName();
471 } else {
472 if (conversation instanceof Conversation) {
473 final MucOptions.User user = ((Conversation) conversation).getMucOptions().findUserByFullJid(message.getCounterpart());
474 if (user != null) {
475 final String dname = getDisplayName(user);
476 if (dname != null) return dname;
477 }
478 }
479 return getDisplayedMucCounterpart(message.getCounterpart());
480 }
481 } else {
482 return contact != null ? contact.getDisplayName() : "";
483 }
484 } else {
485 if (conversation instanceof Conversation && conversation.getMode() == Conversation.MODE_MULTI) {
486 return ((Conversation) conversation).getMucOptions().getSelf().getNick();
487 } else {
488 final Account account = conversation.getAccount();
489 final Jid jid = account.getJid();
490 final String displayName = account.getDisplayName();
491 if (Strings.isNullOrEmpty(displayName)) {
492 return jid.getLocal() != null ? jid.getLocal() : jid.getDomain().toString();
493 } else {
494 return displayName;
495 }
496
497 }
498 }
499 }
500
501 public static String getMessageHint(final Context context,final Conversation conversation) {
502 return switch (conversation.getNextEncryption()) {
503 case Message.ENCRYPTION_NONE -> {
504 if (Config.multipleEncryptionChoices()) {
505 yield context.getString(R.string.send_message);
506 } else {
507 yield context.getString(R.string.send_message_to_x, conversation.getName());
508 }
509 }
510 case Message.ENCRYPTION_AXOLOTL -> {
511 final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
512 if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
513 yield context.getString(R.string.send_omemo_x509_message);
514 } else {
515 yield context.getString(R.string.send_encrypted_message);
516 }
517 }
518 default -> context.getString(R.string.send_encrypted_message);
519 };
520 }
521
522 public static String getDisplayedMucCounterpart(final Jid counterpart) {
523 if (counterpart == null) {
524 return "";
525 } else if (!counterpart.isBareJid()) {
526 return counterpart.getResource().trim();
527 } else {
528 return counterpart.toString().trim();
529 }
530 }
531
532 public static boolean receivedLocationQuestion(final Message message) {
533 if (message == null
534 || message.getStatus() != Message.STATUS_RECEIVED
535 || message.getType() != Message.TYPE_TEXT) {
536 return false;
537 }
538 final String body = Strings.nullToEmpty(message.getBody())
539 .trim()
540 .toLowerCase(Locale.getDefault())
541 .replace("?", "").replace("¿", "");
542 return LOCATION_QUESTIONS.contains(body);
543 }
544
545 public static void setStatus(final TextView textView, Presence.Status status) {
546 final @StringRes int text;
547 final @ColorRes int color =
548 switch (status) {
549 case CHAT -> {
550 text = R.string.presence_chat;
551 yield R.color.green_800;
552 }
553 case ONLINE -> {
554 text = R.string.presence_online;
555 yield R.color.green_800;
556 }
557 case AWAY -> {
558 text = R.string.presence_away;
559 yield R.color.amber_800;
560 }
561 case XA -> {
562 text = R.string.presence_xa;
563 yield R.color.orange_800;
564 }
565 case DND -> {
566 text = R.string.presence_dnd;
567 yield R.color.red_800;
568 }
569 default -> throw new IllegalStateException();
570 };
571 textView.setText(text);
572 textView.setBackgroundTintList(
573 ColorStateList.valueOf(
574 MaterialColors.harmonizeWithPrimary(
575 textView.getContext(),
576 ContextCompat.getColor(textView.getContext(), color))));
577 }
578
579 public static String filesizeToString(long size) {
580 if (size > (1.5 * 1024 * 1024)) {
581 return Math.round(size * 1f / (1024 * 1024)) + " MiB";
582 } else if (size >= 1024) {
583 return Math.round(size * 1f / 1024) + " KiB";
584 } else {
585 return size + " B";
586 }
587 }
588}