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