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