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