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.util.ArrayList;
 12import java.util.Arrays;
 13import java.util.Calendar;
 14import java.util.Date;
 15import java.util.List;
 16import java.util.Locale;
 17
 18import eu.siacs.conversations.Config;
 19import eu.siacs.conversations.R;
 20import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 21import eu.siacs.conversations.entities.Contact;
 22import eu.siacs.conversations.entities.Conversation;
 23import eu.siacs.conversations.entities.ListItem;
 24import eu.siacs.conversations.entities.Message;
 25import eu.siacs.conversations.entities.Presence;
 26import eu.siacs.conversations.entities.Transferable;
 27import eu.siacs.conversations.ui.XmppActivity;
 28import eu.siacs.conversations.xmpp.chatstate.ChatState;
 29import eu.siacs.conversations.xmpp.jid.Jid;
 30
 31public class UIHelper {
 32
 33	private static String BLACK_HEART_SUIT = "\u2665";
 34	private static String HEAVY_BLACK_HEART_SUIT = "\u2764";
 35	private static String WHITE_HEART_SUIT = "\u2661";
 36
 37	public static final List<String> HEARTS = Arrays.asList(BLACK_HEART_SUIT,HEAVY_BLACK_HEART_SUIT,WHITE_HEART_SUIT);
 38
 39	private static final List<String> LOCATION_QUESTIONS = Arrays.asList(
 40			"where are you", //en
 41			"where are you now", //en
 42			"where are you right now", //en
 43			"whats your 20", //en
 44			"what is your 20", //en
 45			"what's your 20", //en
 46			"whats your twenty", //en
 47			"what is your twenty", //en
 48			"what's your twenty", //en
 49			"wo bist du", //de
 50			"wo bist du jetzt", //de
 51			"wo bist du gerade", //de
 52			"wo seid ihr", //de
 53			"wo seid ihr jetzt", //de
 54			"wo seid ihr gerade", //de
 55			"dónde estás", //es
 56			"donde estas" //es
 57		);
 58
 59	private static final List<Character> PUNCTIONATION = Arrays.asList('.',',','?','!',';',':');
 60
 61	private static final int SHORT_DATE_FLAGS = DateUtils.FORMAT_SHOW_DATE
 62		| DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
 63	private static final int FULL_DATE_FLAGS = DateUtils.FORMAT_SHOW_TIME
 64		| DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE;
 65
 66	public static String readableTimeDifference(Context context, long time) {
 67		return readableTimeDifference(context, time, false);
 68	}
 69
 70	public static String readableTimeDifferenceFull(Context context, long time) {
 71		return readableTimeDifference(context, time, true);
 72	}
 73
 74	private static String readableTimeDifference(Context context, long time,
 75			boolean fullDate) {
 76		if (time == 0) {
 77			return context.getString(R.string.just_now);
 78		}
 79		Date date = new Date(time);
 80		long difference = (System.currentTimeMillis() - time) / 1000;
 81		if (difference < 60) {
 82			return context.getString(R.string.just_now);
 83		} else if (difference < 60 * 2) {
 84			return context.getString(R.string.minute_ago);
 85		} else if (difference < 60 * 15) {
 86			return context.getString(R.string.minutes_ago,Math.round(difference / 60.0));
 87		} else if (today(date)) {
 88			java.text.DateFormat df = DateFormat.getTimeFormat(context);
 89			return df.format(date);
 90		} else {
 91			if (fullDate) {
 92				return DateUtils.formatDateTime(context, date.getTime(),
 93						FULL_DATE_FLAGS);
 94			} else {
 95				return DateUtils.formatDateTime(context, date.getTime(),
 96						SHORT_DATE_FLAGS);
 97			}
 98		}
 99	}
100
101	private static boolean today(Date date) {
102		return sameDay(date,new Date(System.currentTimeMillis()));
103	}
104
105	private static boolean sameDay(Date a, Date b) {
106		Calendar cal1 = Calendar.getInstance();
107		Calendar cal2 = Calendar.getInstance();
108		cal1.setTime(a);
109		cal2.setTime(b);
110		return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
111			&& cal1.get(Calendar.DAY_OF_YEAR) == cal2
112			.get(Calendar.DAY_OF_YEAR);
113	}
114
115	public static String lastseen(Context context, boolean active, long time) {
116		long difference = (System.currentTimeMillis() - time) / 1000;
117		active = active && difference <= 300;
118		if (active || difference < 60) {
119			return context.getString(R.string.last_seen_now);
120		} else if (difference < 60 * 2) {
121			return context.getString(R.string.last_seen_min);
122		} else if (difference < 60 * 60) {
123			return context.getString(R.string.last_seen_mins,
124					Math.round(difference / 60.0));
125		} else if (difference < 60 * 60 * 2) {
126			return context.getString(R.string.last_seen_hour);
127		} else if (difference < 60 * 60 * 24) {
128			return context.getString(R.string.last_seen_hours,
129					Math.round(difference / (60.0 * 60.0)));
130		} else if (difference < 60 * 60 * 48) {
131			return context.getString(R.string.last_seen_day);
132		} else {
133			return context.getString(R.string.last_seen_days,
134					Math.round(difference / (60.0 * 60.0 * 24.0)));
135		}
136	}
137
138	public static int getColorForName(String name) {
139		if (name == null || name.isEmpty()) {
140			return 0xFF202020;
141		}
142		int colors[] = {0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5,
143			0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722,
144			0xFF795548, 0xFF607d8b};
145		return colors[(int) ((name.hashCode() & 0xffffffffl) % colors.length)];
146	}
147
148	public static Pair<String,Boolean> getMessagePreview(final Context context, final Message message) {
149		final Transferable d = message.getTransferable();
150		if (d != null ) {
151			switch (d.getStatus()) {
152				case Transferable.STATUS_CHECKING:
153					return new Pair<>(context.getString(R.string.checking_x,
154									getFileDescriptionString(context,message)),true);
155				case Transferable.STATUS_DOWNLOADING:
156					return new Pair<>(context.getString(R.string.receiving_x_file,
157									getFileDescriptionString(context,message),
158									d.getProgress()),true);
159				case Transferable.STATUS_OFFER:
160				case Transferable.STATUS_OFFER_CHECK_FILESIZE:
161					return new Pair<>(context.getString(R.string.x_file_offered_for_download,
162									getFileDescriptionString(context,message)),true);
163				case Transferable.STATUS_DELETED:
164					return new Pair<>(context.getString(R.string.file_deleted),true);
165				case Transferable.STATUS_FAILED:
166					return new Pair<>(context.getString(R.string.file_transmission_failed),true);
167				case Transferable.STATUS_UPLOADING:
168					if (message.getStatus() == Message.STATUS_OFFERED) {
169						return new Pair<>(context.getString(R.string.offering_x_file,
170								getFileDescriptionString(context, message)), true);
171					} else {
172						return new Pair<>(context.getString(R.string.sending_x_file,
173								getFileDescriptionString(context, message)), true);
174					}
175				default:
176					return new Pair<>("",false);
177			}
178		} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
179			return new Pair<>(context.getString(R.string.pgp_message),true);
180		} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
181			return new Pair<>(context.getString(R.string.decryption_failed), true);
182		} else if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
183			if (message.getStatus() == Message.STATUS_RECEIVED) {
184				return new Pair<>(context.getString(R.string.received_x_file,
185							getFileDescriptionString(context, message)), true);
186			} else {
187				return new Pair<>(getFileDescriptionString(context,message),true);
188			}
189		} else {
190			final String body = message.getBody();
191			if (body.startsWith(Message.ME_COMMAND)) {
192				return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
193						UIHelper.getMessageDisplayName(message) + " "), false);
194			} else if (GeoHelper.isGeoUri(message.getBody())) {
195				if (message.getStatus() == Message.STATUS_RECEIVED) {
196					return new Pair<>(context.getString(R.string.received_location), true);
197				} else {
198					return new Pair<>(context.getString(R.string.location), true);
199				}
200			} else if (message.treatAsDownloadable() == Message.Decision.MUST) {
201				return new Pair<>(context.getString(R.string.x_file_offered_for_download,
202						getFileDescriptionString(context,message)),true);
203			} else {
204				String[] lines = body.split("\n");
205				StringBuilder builder = new StringBuilder();
206				for(String l : lines) {
207					if (l.length() > 0) {
208						char first = l.charAt(0);
209						if ((first != '>' || !isPositionFollowedByQuoteableCharacter(l,0)) && first != '\u00bb') {
210							String line = l.trim();
211							if (line.isEmpty()) {
212								continue;
213							}
214							char last = line.charAt(line.length()-1);
215							if (builder.length() != 0) {
216								builder.append(' ');
217							}
218							builder.append(line);
219							if (!PUNCTIONATION.contains(last)) {
220								break;
221							}
222						}
223					}
224				}
225				if (builder.length() == 0) {
226					builder.append(body.trim());
227				}
228				return new Pair<>(builder.length() > 256 ? builder.substring(0,256) : builder.toString(), false);
229			}
230		}
231	}
232
233	public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
234		return !isPositionFollowedByNumber(body, pos) && !isPositionFollowedByBigGrin(body,pos);
235	}
236
237	private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
238		boolean previousWasNumber = false;
239		for (int i = pos +1; i < body.length(); i++) {
240			char c = body.charAt(i);
241			if (Character.isDigit(body.charAt(i))) {
242				previousWasNumber = true;
243			} else if (previousWasNumber && (c == '.' || c == ',')) {
244				previousWasNumber = false;
245			} else {
246				return Character.isWhitespace(c) && previousWasNumber;
247			}
248		}
249		return previousWasNumber;
250	}
251
252	private static boolean isPositionFollowedByBigGrin(CharSequence body, int pos) {
253		return body.length() <= pos + 1
254				|| ((body.charAt(pos+1) == '<') && (body.length() == pos+2 || Character.isWhitespace(body.charAt(pos+2))));
255	}
256
257	public static String getFileDescriptionString(final Context context, final Message message) {
258		if (message.getType() == Message.TYPE_IMAGE) {
259			return context.getString(R.string.image);
260		}
261		final String mime = message.getMimeType();
262		if (mime == null) {
263			return context.getString(R.string.file);
264		} else if (mime.startsWith("audio/")) {
265			return context.getString(R.string.audio);
266		} else if(mime.startsWith("video/")) {
267			return context.getString(R.string.video);
268		} else if (mime.startsWith("image/")) {
269			return context.getString(R.string.image);
270		} else if (mime.contains("pdf")) {
271			return context.getString(R.string.pdf_document)	;
272		} else if (mime.contains("application/vnd.android.package-archive")) {
273			return context.getString(R.string.apk)	;
274		} else if (mime.contains("vcard")) {
275			return context.getString(R.string.vcard)	;
276		} else {
277			return mime;
278		}
279	}
280
281	public static String getMessageDisplayName(final Message message) {
282		final Conversation conversation = message.getConversation();
283		if (message.getStatus() == Message.STATUS_RECEIVED) {
284			final Contact contact = message.getContact();
285			if (conversation.getMode() == Conversation.MODE_MULTI) {
286				if (contact != null) {
287					return contact.getDisplayName();
288				} else {
289					return getDisplayedMucCounterpart(message.getCounterpart());
290				}
291			} else {
292				return contact != null ? contact.getDisplayName() : "";
293			}
294		} else {
295			if (conversation.getMode() == Conversation.MODE_MULTI) {
296				return conversation.getMucOptions().getSelf().getName();
297			} else {
298				final Jid jid = conversation.getAccount().getJid();
299				return jid.hasLocalpart() ? jid.getLocalpart() : jid.toDomainJid().toString();
300			}
301		}
302	}
303
304	public static String getMessageHint(Context context, Conversation conversation) {
305		switch (conversation.getNextEncryption()) {
306			case Message.ENCRYPTION_NONE:
307				if (Config.multipleEncryptionChoices()) {
308					return context.getString(R.string.send_unencrypted_message);
309				} else {
310					return context.getString(R.string.send_message_to_x,conversation.getName());
311				}
312			case Message.ENCRYPTION_OTR:
313				return context.getString(R.string.send_otr_message);
314			case Message.ENCRYPTION_AXOLOTL:
315				AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
316				if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
317					return context.getString(R.string.send_omemo_x509_message);
318				} else {
319					return context.getString(R.string.send_omemo_message);
320				}
321			case Message.ENCRYPTION_PGP:
322				return context.getString(R.string.send_pgp_message);
323			default:
324				return "";
325		}
326	}
327
328	public static String getDisplayedMucCounterpart(final Jid counterpart) {
329		if (counterpart==null) {
330			return "";
331		} else if (!counterpart.isBareJid()) {
332			return counterpart.getResourcepart().trim();
333		} else {
334			return counterpart.toString().trim();
335		}
336	}
337
338	public static boolean receivedLocationQuestion(Message message) {
339		if (message == null
340				|| message.getStatus() != Message.STATUS_RECEIVED
341				|| message.getType() != Message.TYPE_TEXT) {
342			return false;
343		}
344		String body = message.getBody() == null ? null : message.getBody().trim().toLowerCase(Locale.getDefault());
345		body = body.replace("?","").replace("¿","");
346		return LOCATION_QUESTIONS.contains(body);
347	}
348
349	public static ListItem.Tag getTagForStatus(Context context, Presence.Status status) {
350		switch (status) {
351			case CHAT:
352				return new ListItem.Tag(context.getString(R.string.presence_chat), 0xff259b24);
353			case AWAY:
354				return new ListItem.Tag(context.getString(R.string.presence_away), 0xffff9800);
355			case XA:
356				return new ListItem.Tag(context.getString(R.string.presence_xa), 0xfff44336);
357			case DND:
358				return new ListItem.Tag(context.getString(R.string.presence_dnd), 0xfff44336);
359			default:
360				return new ListItem.Tag(context.getString(R.string.presence_online), 0xff259b24);
361		}
362	}
363
364	public static String tranlasteType(Context context, String type) {
365		switch (type.toLowerCase()) {
366			case "pc":
367				return context.getString(R.string.type_pc);
368			case "phone":
369				return context.getString(R.string.type_phone);
370			case "tablet":
371				return context.getString(R.string.type_tablet);
372			case "web":
373				return context.getString(R.string.type_web);
374			case "console":
375				return context.getString(R.string.type_console);
376			default:
377				return type;
378		}
379	}
380
381	public static boolean showIconsInPopup(PopupMenu attachFilePopup) {
382		try {
383			Field field = attachFilePopup.getClass().getDeclaredField("mPopup");
384			field.setAccessible(true);
385			Object menuPopupHelper = field.get(attachFilePopup);
386			Class<?> cls = Class.forName("com.android.internal.view.menu.MenuPopupHelper");
387			Method method = cls.getDeclaredMethod("setForceShowIcon", new Class[]{boolean.class});
388			method.setAccessible(true);
389			method.invoke(menuPopupHelper, new Object[]{true});
390			return true;
391		} catch (Exception e) {
392			return false;
393		}
394	}
395}