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