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