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