UIHelper.java

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