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