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