1package eu.siacs.conversations.utils;
2
3import android.content.Context;
4import android.support.annotation.ColorInt;
5import android.text.SpannableString;
6import android.text.SpannableStringBuilder;
7import android.text.format.DateFormat;
8import android.text.format.DateUtils;
9import android.util.Log;
10import android.util.Pair;
11import android.widget.PopupMenu;
12
13import java.lang.reflect.Field;
14import java.lang.reflect.Method;
15import java.math.BigInteger;
16import java.security.MessageDigest;
17import java.util.ArrayList;
18import java.util.Arrays;
19import java.util.Calendar;
20import java.util.Date;
21import java.util.List;
22import java.util.Locale;
23
24import eu.siacs.conversations.Config;
25import eu.siacs.conversations.R;
26import eu.siacs.conversations.crypto.axolotl.AxolotlService;
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.Transferable;
35import eu.siacs.conversations.services.ExportBackupService;
36import rocks.xmpp.addr.Jid;
37
38public class UIHelper {
39
40 private static 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 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 return new Pair<>(context.getString(message.getStatus() == Message.STATUS_RECEIVED ? R.string.incoming_call : R.string.outgoing_call), true);
304 } else {
305 final String body = MessageUtils.filterLtrRtl(message.getBody());
306 if (body.startsWith(Message.ME_COMMAND)) {
307 return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
308 UIHelper.getMessageDisplayName(message) + " "), false);
309 } else if (message.isGeoUri()) {
310 return new Pair<>(context.getString(R.string.location), true);
311 } else if (message.treatAsDownloadable() || MessageUtils.unInitiatedButKnownSize(message)) {
312 return new Pair<>(context.getString(R.string.x_file_offered_for_download,
313 getFileDescriptionString(context, message)), true);
314 } else {
315 SpannableStringBuilder styledBody = new SpannableStringBuilder(body);
316 if (textColor != 0) {
317 StylingHelper.format(styledBody, 0, styledBody.length() - 1, textColor);
318 }
319 SpannableStringBuilder builder = new SpannableStringBuilder();
320 for (CharSequence l : CharSequenceUtils.split(styledBody, '\n')) {
321 if (l.length() > 0) {
322 if (l.toString().equals("```")) {
323 continue;
324 }
325 char first = l.charAt(0);
326 if ((first != '>' || !isPositionFollowedByQuoteableCharacter(l, 0)) && first != '\u00bb') {
327 CharSequence line = CharSequenceUtils.trim(l);
328 if (line.length() == 0) {
329 continue;
330 }
331 char last = line.charAt(line.length() - 1);
332 if (builder.length() != 0) {
333 builder.append(' ');
334 }
335 builder.append(line);
336 if (!PUNCTIONATION.contains(last)) {
337 break;
338 }
339 }
340 }
341 }
342 if (builder.length() == 0) {
343 builder.append(body.trim());
344 }
345 return new Pair<>(builder, false);
346 }
347 }
348 }
349
350 public static boolean isLastLineQuote(String body) {
351 if (body.endsWith("\n")) {
352 return false;
353 }
354 String[] lines = body.split("\n");
355 if (lines.length == 0) {
356 return false;
357 }
358 String line = lines[lines.length - 1];
359 if (line.isEmpty()) {
360 return false;
361 }
362 char first = line.charAt(0);
363 return first == '>' && isPositionFollowedByQuoteableCharacter(line,0) || first == '\u00bb';
364 }
365
366 public static CharSequence shorten(CharSequence input) {
367 return input.length() > 256 ? StylingHelper.subSequence(input, 0, 256) : input;
368 }
369
370 public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
371 return !isPositionFollowedByNumber(body, pos)
372 && !isPositionFollowedByEmoticon(body, pos)
373 && !isPositionFollowedByEquals(body, pos);
374 }
375
376 private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
377 boolean previousWasNumber = false;
378 for (int i = pos + 1; i < body.length(); i++) {
379 char c = body.charAt(i);
380 if (Character.isDigit(body.charAt(i))) {
381 previousWasNumber = true;
382 } else if (previousWasNumber && (c == '.' || c == ',')) {
383 previousWasNumber = false;
384 } else {
385 return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
386 }
387 }
388 return previousWasNumber;
389 }
390
391 private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
392 return body.length() > pos + 1 && body.charAt(pos + 1) == '=';
393 }
394
395 private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
396 if (body.length() <= pos + 1) {
397 return false;
398 } else {
399 final char first = body.charAt(pos + 1);
400 return first == ';'
401 || first == ':'
402 || closingBeforeWhitespace(body, pos + 1);
403 }
404 }
405
406 private static boolean closingBeforeWhitespace(CharSequence body, int pos) {
407 for (int i = pos; i < body.length(); ++i) {
408 final char c = body.charAt(i);
409 if (Character.isWhitespace(c)) {
410 return false;
411 } else if (c == '<' || c == '>') {
412 return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
413 }
414 }
415 return false;
416 }
417
418 public static boolean isPositionFollowedByQuote(CharSequence body, int pos) {
419 if (body.length() <= pos + 1 || Character.isWhitespace(body.charAt(pos + 1))) {
420 return false;
421 }
422 boolean previousWasWhitespace = false;
423 for (int i = pos + 1; i < body.length(); i++) {
424 char c = body.charAt(i);
425 if (c == '\n' || c == '»') {
426 return false;
427 } else if (c == '«' && !previousWasWhitespace) {
428 return true;
429 } else {
430 previousWasWhitespace = Character.isWhitespace(c);
431 }
432 }
433 return false;
434 }
435
436 public static String getDisplayName(MucOptions.User user) {
437 Contact contact = user.getContact();
438 if (contact != null) {
439 return contact.getDisplayName();
440 } else {
441 final String name = user.getName();
442 if (name != null) {
443 return name;
444 }
445 final Jid realJid = user.getRealJid();
446 if (realJid != null) {
447 return JidHelper.localPartOrFallback(realJid);
448 }
449 return null;
450 }
451 }
452
453 public static String concatNames(List<MucOptions.User> users) {
454 return concatNames(users, users.size());
455 }
456
457 public static String concatNames(List<MucOptions.User> users, int max) {
458 StringBuilder builder = new StringBuilder();
459 final boolean shortNames = users.size() >= 3;
460 for (int i = 0; i < Math.min(users.size(), max); ++i) {
461 if (builder.length() != 0) {
462 builder.append(", ");
463 }
464 final String name = UIHelper.getDisplayName(users.get(i));
465 if (name != null) {
466 builder.append(shortNames ? name.split("\\s+")[0] : name);
467 }
468 }
469 return builder.toString();
470 }
471
472 public static String getFileDescriptionString(final Context context, final Message message) {
473 if (message.getType() == Message.TYPE_IMAGE) {
474 return context.getString(R.string.image);
475 }
476 final String mime = message.getMimeType();
477 if (mime == null) {
478 return context.getString(R.string.file);
479 } else if (mime.startsWith("audio/")) {
480 return context.getString(R.string.audio);
481 } else if (mime.startsWith("video/")) {
482 return context.getString(R.string.video);
483 } else if (mime.equals("image/gif")) {
484 return context.getString(R.string.gif);
485 } else if (mime.startsWith("image/")) {
486 return context.getString(R.string.image);
487 } else if (mime.contains("pdf")) {
488 return context.getString(R.string.pdf_document);
489 } else if (mime.equals("application/vnd.android.package-archive")) {
490 return context.getString(R.string.apk);
491 } else if (mime.equals(ExportBackupService.MIME_TYPE)) {
492 return context.getString(R.string.conversations_backup);
493 } else if (mime.contains("vcard")) {
494 return context.getString(R.string.vcard);
495 } else if (mime.equals("text/x-vcalendar") || mime.equals("text/calendar")) {
496 return context.getString(R.string.event);
497 } else if (mime.equals("application/epub+zip") || mime.equals("application/vnd.amazon.mobi8-ebook")) {
498 return context.getString(R.string.ebook);
499 } else {
500 return mime;
501 }
502 }
503
504 public static String getMessageDisplayName(final Message message) {
505 final Conversational conversation = message.getConversation();
506 if (message.getStatus() == Message.STATUS_RECEIVED) {
507 final Contact contact = message.getContact();
508 if (conversation.getMode() == Conversation.MODE_MULTI) {
509 if (contact != null) {
510 return contact.getDisplayName();
511 } else {
512 return getDisplayedMucCounterpart(message.getCounterpart());
513 }
514 } else {
515 return contact != null ? contact.getDisplayName() : "";
516 }
517 } else {
518 if (conversation instanceof Conversation && conversation.getMode() == Conversation.MODE_MULTI) {
519 return ((Conversation) conversation).getMucOptions().getSelf().getName();
520 } else {
521 final Jid jid = conversation.getAccount().getJid();
522 return jid.getLocal() != null ? jid.getLocal() : Jid.ofDomain(jid.getDomain()).toString();
523 }
524 }
525 }
526
527 public static String getMessageHint(Context context, Conversation conversation) {
528 switch (conversation.getNextEncryption()) {
529 case Message.ENCRYPTION_NONE:
530 if (Config.multipleEncryptionChoices()) {
531 return context.getString(R.string.send_unencrypted_message);
532 } else {
533 return context.getString(R.string.send_message_to_x, conversation.getName());
534 }
535 case Message.ENCRYPTION_AXOLOTL:
536 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
537 if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
538 return context.getString(R.string.send_omemo_x509_message);
539 } else {
540 return context.getString(R.string.send_omemo_message);
541 }
542 case Message.ENCRYPTION_PGP:
543 return context.getString(R.string.send_pgp_message);
544 default:
545 return "";
546 }
547 }
548
549 public static String getDisplayedMucCounterpart(final Jid counterpart) {
550 if (counterpart == null) {
551 return "";
552 } else if (!counterpart.isBareJid()) {
553 return counterpart.getResource().trim();
554 } else {
555 return counterpart.toString().trim();
556 }
557 }
558
559 public static boolean receivedLocationQuestion(Message message) {
560 if (message == null
561 || message.getStatus() != Message.STATUS_RECEIVED
562 || message.getType() != Message.TYPE_TEXT) {
563 return false;
564 }
565 String body = message.getBody() == null ? null : message.getBody().trim().toLowerCase(Locale.getDefault());
566 body = body.replace("?", "").replace("¿", "");
567 return LOCATION_QUESTIONS.contains(body);
568 }
569
570 public static ListItem.Tag getTagForStatus(Context context, Presence.Status status) {
571 switch (status) {
572 case CHAT:
573 return new ListItem.Tag(context.getString(R.string.presence_chat), 0xff259b24);
574 case AWAY:
575 return new ListItem.Tag(context.getString(R.string.presence_away), 0xffff9800);
576 case XA:
577 return new ListItem.Tag(context.getString(R.string.presence_xa), 0xfff44336);
578 case DND:
579 return new ListItem.Tag(context.getString(R.string.presence_dnd), 0xfff44336);
580 default:
581 return new ListItem.Tag(context.getString(R.string.presence_online), 0xff259b24);
582 }
583 }
584
585 public static String filesizeToString(long size) {
586 if (size > (1.5 * 1024 * 1024)) {
587 return Math.round(size * 1f / (1024 * 1024)) + " MiB";
588 } else if (size >= 1024) {
589 return Math.round(size * 1f / 1024) + " KiB";
590 } else {
591 return size + " B";
592 }
593 }
594}