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