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.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
281			if (message.getStatus() == Message.STATUS_RECEIVED) {
282				return new Pair<>(context.getString(R.string.received_x_file,
283						getFileDescriptionString(context, message)), true);
284			} else {
285				return new Pair<>(getFileDescriptionString(context, message), true);
286			}
287		} else {
288			final String body = message.getBody();
289			if (body.startsWith(Message.ME_COMMAND)) {
290				return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
291						UIHelper.getMessageDisplayName(message) + " "), false);
292			} else if (message.isGeoUri()) {
293				if (message.getStatus() == Message.STATUS_RECEIVED) {
294					return new Pair<>(context.getString(R.string.received_location), true);
295				} else {
296					return new Pair<>(context.getString(R.string.location), true);
297				}
298			} else if (message.treatAsDownloadable()) {
299				return new Pair<>(context.getString(R.string.x_file_offered_for_download,
300						getFileDescriptionString(context, message)), true);
301			} else {
302				String[] lines = body.split("\n");
303				StringBuilder builder = new StringBuilder();
304				for (String l : lines) {
305					if (l.length() > 0) {
306						char first = l.charAt(0);
307						if ((first != '>' || !isPositionFollowedByQuoteableCharacter(l, 0)) && first != '\u00bb') {
308							String line = l.trim();
309							if (line.isEmpty()) {
310								continue;
311							}
312							char last = line.charAt(line.length() - 1);
313							if (builder.length() != 0) {
314								builder.append(' ');
315							}
316							builder.append(line);
317							if (!PUNCTIONATION.contains(last)) {
318								break;
319							}
320						}
321					}
322				}
323				if (builder.length() == 0) {
324					builder.append(body.trim());
325				}
326				return new Pair<>(builder.length() > 256 ? builder.substring(0, 256) : builder.toString(), false);
327			}
328		}
329	}
330
331	public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
332		return !isPositionFollowedByNumber(body, pos)
333				&& !isPositionFollowedByEmoticon(body, pos)
334				&& !isPositionFollowedByEquals(body, pos);
335	}
336
337	private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
338		boolean previousWasNumber = false;
339		for (int i = pos + 1; i < body.length(); i++) {
340			char c = body.charAt(i);
341			if (Character.isDigit(body.charAt(i))) {
342				previousWasNumber = true;
343			} else if (previousWasNumber && (c == '.' || c == ',')) {
344				previousWasNumber = false;
345			} else {
346				return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
347			}
348		}
349		return previousWasNumber;
350	}
351
352	private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
353		return body.length() > pos + 1 && body.charAt(pos + 1) == '=';
354	}
355
356	private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
357		if (body.length() <= pos + 1) {
358			return false;
359		} else {
360			final char first = body.charAt(pos + 1);
361			return first == ';'
362					|| first == ':'
363					|| closingBeforeWhitespace(body, pos + 1);
364		}
365	}
366
367	private static boolean closingBeforeWhitespace(CharSequence body, int pos) {
368		for (int i = pos; i < body.length(); ++i) {
369			final char c = body.charAt(i);
370			if (Character.isWhitespace(c)) {
371				return false;
372			} else if (c == '<' || c == '>') {
373				return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
374			}
375		}
376		return false;
377	}
378
379	public static boolean isPositionFollowedByQuote(CharSequence body, int pos) {
380		if (body.length() <= pos + 1 || Character.isWhitespace(body.charAt(pos + 1))) {
381			return false;
382		}
383		boolean previousWasWhitespace = false;
384		for (int i = pos + 1; i < body.length(); i++) {
385			char c = body.charAt(i);
386			if (c == '\n' || c == '»') {
387				return false;
388			} else if (c == '«' && !previousWasWhitespace) {
389				return true;
390			} else {
391				previousWasWhitespace = Character.isWhitespace(c);
392			}
393		}
394		return false;
395	}
396
397	public static String getDisplayName(MucOptions.User user) {
398		Contact contact = user.getContact();
399		if (contact != null) {
400			return contact.getDisplayName();
401		} else {
402			final String name = user.getName();
403			if (name != null) {
404				return name;
405			}
406			final Jid realJid = user.getRealJid();
407			if (realJid != null) {
408				return JidHelper.localPartOrFallback(realJid);
409			}
410			return null;
411		}
412	}
413
414	public static String concatNames(List<MucOptions.User> users) {
415		return concatNames(users, users.size());
416	}
417
418	public static String concatNames(List<MucOptions.User> users, int max) {
419		StringBuilder builder = new StringBuilder();
420		final boolean shortNames = users.size() >= 3;
421		for (int i = 0; i < Math.max(users.size(), max); ++i) {
422			if (builder.length() != 0) {
423				builder.append(", ");
424			}
425			final String name = UIHelper.getDisplayName(users.get(i));
426			builder.append(shortNames ? name.split("\\s+")[0] : name);
427		}
428		return builder.toString();
429	}
430
431	public static String getFileDescriptionString(final Context context, final Message message) {
432		if (message.getType() == Message.TYPE_IMAGE) {
433			return context.getString(R.string.image);
434		}
435		final String mime = message.getMimeType();
436		if (mime == null) {
437			return context.getString(R.string.file);
438		} else if (mime.startsWith("audio/")) {
439			return context.getString(R.string.audio);
440		} else if (mime.startsWith("video/")) {
441			return context.getString(R.string.video);
442		} else if (mime.startsWith("image/")) {
443			return context.getString(R.string.image);
444		} else if (mime.contains("pdf")) {
445			return context.getString(R.string.pdf_document);
446		} else if (mime.contains("application/vnd.android.package-archive")) {
447			return context.getString(R.string.apk);
448		} else if (mime.contains("vcard")) {
449			return context.getString(R.string.vcard);
450		} else {
451			return mime;
452		}
453	}
454
455	public static String getMessageDisplayName(final Message message) {
456		final Conversation conversation = message.getConversation();
457		if (message.getStatus() == Message.STATUS_RECEIVED) {
458			final Contact contact = message.getContact();
459			if (conversation.getMode() == Conversation.MODE_MULTI) {
460				if (contact != null) {
461					return contact.getDisplayName();
462				} else {
463					return getDisplayedMucCounterpart(message.getCounterpart());
464				}
465			} else {
466				return contact != null ? contact.getDisplayName() : "";
467			}
468		} else {
469			if (conversation.getMode() == Conversation.MODE_MULTI) {
470				return conversation.getMucOptions().getSelf().getName();
471			} else {
472				final Jid jid = conversation.getAccount().getJid();
473				return jid.getLocal() != null ? jid.getLocal() : Jid.ofDomain(jid.getDomain()).toString();
474			}
475		}
476	}
477
478	public static String getMessageHint(Context context, Conversation conversation) {
479		switch (conversation.getNextEncryption()) {
480			case Message.ENCRYPTION_NONE:
481				if (Config.multipleEncryptionChoices()) {
482					return context.getString(R.string.send_unencrypted_message);
483				} else {
484					return context.getString(R.string.send_message_to_x, conversation.getName());
485				}
486			case Message.ENCRYPTION_AXOLOTL:
487				AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
488				if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
489					return context.getString(R.string.send_omemo_x509_message);
490				} else {
491					return context.getString(R.string.send_omemo_message);
492				}
493			case Message.ENCRYPTION_PGP:
494				return context.getString(R.string.send_pgp_message);
495			default:
496				return "";
497		}
498	}
499
500	public static String getDisplayedMucCounterpart(final Jid counterpart) {
501		if (counterpart == null) {
502			return "";
503		} else if (!counterpart.isBareJid()) {
504			return counterpart.getResource().trim();
505		} else {
506			return counterpart.toString().trim();
507		}
508	}
509
510	public static boolean receivedLocationQuestion(Message message) {
511		if (message == null
512				|| message.getStatus() != Message.STATUS_RECEIVED
513				|| message.getType() != Message.TYPE_TEXT) {
514			return false;
515		}
516		String body = message.getBody() == null ? null : message.getBody().trim().toLowerCase(Locale.getDefault());
517		body = body.replace("?", "").replace("¿", "");
518		return LOCATION_QUESTIONS.contains(body);
519	}
520
521	public static ListItem.Tag getTagForStatus(Context context, Presence.Status status) {
522		switch (status) {
523			case CHAT:
524				return new ListItem.Tag(context.getString(R.string.presence_chat), 0xff259b24);
525			case AWAY:
526				return new ListItem.Tag(context.getString(R.string.presence_away), 0xffff9800);
527			case XA:
528				return new ListItem.Tag(context.getString(R.string.presence_xa), 0xfff44336);
529			case DND:
530				return new ListItem.Tag(context.getString(R.string.presence_dnd), 0xfff44336);
531			default:
532				return new ListItem.Tag(context.getString(R.string.presence_online), 0xff259b24);
533		}
534	}
535}