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