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