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