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 public static boolean today(long date) {
104 return sameDay(date,System.currentTimeMillis());
105 }
106
107 public static boolean yesterday(long date) {
108 Calendar cal1 = Calendar.getInstance();
109 Calendar cal2 = Calendar.getInstance();
110 cal1.add(Calendar.DAY_OF_YEAR,-1);
111 cal2.setTime(new Date(date));
112 return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
113 && cal1.get(Calendar.DAY_OF_YEAR) == cal2
114 .get(Calendar.DAY_OF_YEAR);
115 }
116
117 public static boolean sameDay(long a, long b) {
118 return sameDay(new Date(a),new Date(b));
119 }
120
121 private static boolean sameDay(Date a, Date b) {
122 Calendar cal1 = Calendar.getInstance();
123 Calendar cal2 = Calendar.getInstance();
124 cal1.setTime(a);
125 cal2.setTime(b);
126 return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
127 && cal1.get(Calendar.DAY_OF_YEAR) == cal2
128 .get(Calendar.DAY_OF_YEAR);
129 }
130
131 public static String lastseen(Context context, boolean active, long time) {
132 long difference = (System.currentTimeMillis() - time) / 1000;
133 if (active) {
134 return context.getString(R.string.online_right_now);
135 } else if (difference < 60) {
136 return context.getString(R.string.last_seen_now);
137 } else if (difference < 60 * 2) {
138 return context.getString(R.string.last_seen_min);
139 } else if (difference < 60 * 60) {
140 return context.getString(R.string.last_seen_mins,
141 Math.round(difference / 60.0));
142 } else if (difference < 60 * 60 * 2) {
143 return context.getString(R.string.last_seen_hour);
144 } else if (difference < 60 * 60 * 24) {
145 return context.getString(R.string.last_seen_hours,
146 Math.round(difference / (60.0 * 60.0)));
147 } else if (difference < 60 * 60 * 48) {
148 return context.getString(R.string.last_seen_day);
149 } else {
150 return context.getString(R.string.last_seen_days,
151 Math.round(difference / (60.0 * 60.0 * 24.0)));
152 }
153 }
154
155 public static int getColorForName(String name) {
156 if (name == null || name.isEmpty()) {
157 return 0xFF202020;
158 }
159 int colors[] = {0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5,
160 0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722,
161 0xFF795548, 0xFF607d8b};
162 return colors[(int) ((name.hashCode() & 0xffffffffl) % colors.length)];
163 }
164
165 public static Pair<String,Boolean> getMessagePreview(final Context context, final Message message) {
166 final Transferable d = message.getTransferable();
167 if (d != null ) {
168 switch (d.getStatus()) {
169 case Transferable.STATUS_CHECKING:
170 return new Pair<>(context.getString(R.string.checking_x,
171 getFileDescriptionString(context,message)),true);
172 case Transferable.STATUS_DOWNLOADING:
173 return new Pair<>(context.getString(R.string.receiving_x_file,
174 getFileDescriptionString(context,message),
175 d.getProgress()),true);
176 case Transferable.STATUS_OFFER:
177 case Transferable.STATUS_OFFER_CHECK_FILESIZE:
178 return new Pair<>(context.getString(R.string.x_file_offered_for_download,
179 getFileDescriptionString(context,message)),true);
180 case Transferable.STATUS_DELETED:
181 return new Pair<>(context.getString(R.string.file_deleted),true);
182 case Transferable.STATUS_FAILED:
183 return new Pair<>(context.getString(R.string.file_transmission_failed),true);
184 case Transferable.STATUS_UPLOADING:
185 if (message.getStatus() == Message.STATUS_OFFERED) {
186 return new Pair<>(context.getString(R.string.offering_x_file,
187 getFileDescriptionString(context, message)), true);
188 } else {
189 return new Pair<>(context.getString(R.string.sending_x_file,
190 getFileDescriptionString(context, message)), true);
191 }
192 default:
193 return new Pair<>("",false);
194 }
195 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
196 return new Pair<>(context.getString(R.string.pgp_message),true);
197 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
198 return new Pair<>(context.getString(R.string.decryption_failed), true);
199 } else if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
200 if (message.getStatus() == Message.STATUS_RECEIVED) {
201 return new Pair<>(context.getString(R.string.received_x_file,
202 getFileDescriptionString(context, message)), true);
203 } else {
204 return new Pair<>(getFileDescriptionString(context,message),true);
205 }
206 } else {
207 final String body = message.getBody();
208 if (body.startsWith(Message.ME_COMMAND)) {
209 return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
210 UIHelper.getMessageDisplayName(message) + " "), false);
211 } else if (GeoHelper.isGeoUri(message.getBody())) {
212 if (message.getStatus() == Message.STATUS_RECEIVED) {
213 return new Pair<>(context.getString(R.string.received_location), true);
214 } else {
215 return new Pair<>(context.getString(R.string.location), true);
216 }
217 } else if (message.treatAsDownloadable()) {
218 return new Pair<>(context.getString(R.string.x_file_offered_for_download,
219 getFileDescriptionString(context,message)),true);
220 } else {
221 String[] lines = body.split("\n");
222 StringBuilder builder = new StringBuilder();
223 for(String l : lines) {
224 if (l.length() > 0) {
225 char first = l.charAt(0);
226 if ((first != '>' || !isPositionFollowedByQuoteableCharacter(l,0)) && first != '\u00bb') {
227 String line = l.trim();
228 if (line.isEmpty()) {
229 continue;
230 }
231 char last = line.charAt(line.length()-1);
232 if (builder.length() != 0) {
233 builder.append(' ');
234 }
235 builder.append(line);
236 if (!PUNCTIONATION.contains(last)) {
237 break;
238 }
239 }
240 }
241 }
242 if (builder.length() == 0) {
243 builder.append(body.trim());
244 }
245 return new Pair<>(builder.length() > 256 ? builder.substring(0,256) : builder.toString(), false);
246 }
247 }
248 }
249
250 public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
251 return !isPositionFollowedByNumber(body, pos)
252 && !isPositionFollowedByEmoticon(body,pos)
253 && !isPositionFollowedByEquals(body,pos);
254 }
255
256 private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
257 boolean previousWasNumber = false;
258 for (int i = pos +1; i < body.length(); i++) {
259 char c = body.charAt(i);
260 if (Character.isDigit(body.charAt(i))) {
261 previousWasNumber = true;
262 } else if (previousWasNumber && (c == '.' || c == ',')) {
263 previousWasNumber = false;
264 } else {
265 return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
266 }
267 }
268 return previousWasNumber;
269 }
270
271 private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
272 return body.length() > pos + 1 && body.charAt(pos+1) == '=';
273 }
274
275 private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
276 if (body.length() <= pos +1) {
277 return false;
278 } else {
279 final char first = body.charAt(pos +1);
280 return first == ';'
281 || first == ':'
282 || smallerThanBeforeWhitespace(body,pos+1);
283 }
284 }
285
286 private static boolean smallerThanBeforeWhitespace(CharSequence body, int pos) {
287 for(int i = pos; i < body.length(); ++i) {
288 final char c = body.charAt(i);
289 if (Character.isWhitespace(c)) {
290 return false;
291 } else if (c == '<') {
292 return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
293 }
294 }
295 return false;
296 }
297
298 public static boolean isPositionFollowedByQuote(CharSequence body, int pos) {
299 if (body.length() <= pos + 1 || Character.isWhitespace(body.charAt(pos+1))) {
300 return false;
301 }
302 boolean previousWasWhitespace = false;
303 for (int i = pos +1; i < body.length(); i++) {
304 char c = body.charAt(i);
305 if (c == '\n' || c == '»') {
306 return false;
307 } else if (c == '«' && !previousWasWhitespace) {
308 return true;
309 } else {
310 previousWasWhitespace = Character.isWhitespace(c);
311 }
312 }
313 return false;
314 }
315
316 public static String getDisplayName(MucOptions.User user) {
317 Contact contact = user.getContact();
318 if (contact != null) {
319 return contact.getDisplayName();
320 } else {
321 return user.getName();
322 }
323 }
324
325 public static String getFileDescriptionString(final Context context, final Message message) {
326 if (message.getType() == Message.TYPE_IMAGE) {
327 return context.getString(R.string.image);
328 }
329 final String mime = message.getMimeType();
330 if (mime == null) {
331 return context.getString(R.string.file);
332 } else if (mime.startsWith("audio/")) {
333 return context.getString(R.string.audio);
334 } else if(mime.startsWith("video/")) {
335 return context.getString(R.string.video);
336 } else if (mime.startsWith("image/")) {
337 return context.getString(R.string.image);
338 } else if (mime.contains("pdf")) {
339 return context.getString(R.string.pdf_document) ;
340 } else if (mime.contains("application/vnd.android.package-archive")) {
341 return context.getString(R.string.apk) ;
342 } else if (mime.contains("vcard")) {
343 return context.getString(R.string.vcard) ;
344 } else {
345 return mime;
346 }
347 }
348
349 public static String getMessageDisplayName(final Message message) {
350 final Conversation conversation = message.getConversation();
351 if (message.getStatus() == Message.STATUS_RECEIVED) {
352 final Contact contact = message.getContact();
353 if (conversation.getMode() == Conversation.MODE_MULTI) {
354 if (contact != null) {
355 return contact.getDisplayName();
356 } else {
357 return getDisplayedMucCounterpart(message.getCounterpart());
358 }
359 } else {
360 return contact != null ? contact.getDisplayName() : "";
361 }
362 } else {
363 if (conversation.getMode() == Conversation.MODE_MULTI) {
364 return conversation.getMucOptions().getSelf().getName();
365 } else {
366 final Jid jid = conversation.getAccount().getJid();
367 return jid.hasLocalpart() ? jid.getLocalpart() : jid.toDomainJid().toString();
368 }
369 }
370 }
371
372 public static String getMessageHint(Context context, Conversation conversation) {
373 switch (conversation.getNextEncryption()) {
374 case Message.ENCRYPTION_NONE:
375 if (Config.multipleEncryptionChoices()) {
376 return context.getString(R.string.send_unencrypted_message);
377 } else {
378 return context.getString(R.string.send_message_to_x,conversation.getName());
379 }
380 case Message.ENCRYPTION_OTR:
381 return context.getString(R.string.send_otr_message);
382 case Message.ENCRYPTION_AXOLOTL:
383 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
384 if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
385 return context.getString(R.string.send_omemo_x509_message);
386 } else {
387 return context.getString(R.string.send_omemo_message);
388 }
389 case Message.ENCRYPTION_PGP:
390 return context.getString(R.string.send_pgp_message);
391 default:
392 return "";
393 }
394 }
395
396 public static String getDisplayedMucCounterpart(final Jid counterpart) {
397 if (counterpart==null) {
398 return "";
399 } else if (!counterpart.isBareJid()) {
400 return counterpart.getResourcepart().trim();
401 } else {
402 return counterpart.toString().trim();
403 }
404 }
405
406 public static boolean receivedLocationQuestion(Message message) {
407 if (message == null
408 || message.getStatus() != Message.STATUS_RECEIVED
409 || message.getType() != Message.TYPE_TEXT) {
410 return false;
411 }
412 String body = message.getBody() == null ? null : message.getBody().trim().toLowerCase(Locale.getDefault());
413 body = body.replace("?","").replace("¿","");
414 return LOCATION_QUESTIONS.contains(body);
415 }
416
417 public static ListItem.Tag getTagForStatus(Context context, Presence.Status status) {
418 switch (status) {
419 case CHAT:
420 return new ListItem.Tag(context.getString(R.string.presence_chat), 0xff259b24);
421 case AWAY:
422 return new ListItem.Tag(context.getString(R.string.presence_away), 0xffff9800);
423 case XA:
424 return new ListItem.Tag(context.getString(R.string.presence_xa), 0xfff44336);
425 case DND:
426 return new ListItem.Tag(context.getString(R.string.presence_dnd), 0xfff44336);
427 default:
428 return new ListItem.Tag(context.getString(R.string.presence_online), 0xff259b24);
429 }
430 }
431
432 public static String tranlasteType(Context context, String type) {
433 switch (type.toLowerCase()) {
434 case "pc":
435 return context.getString(R.string.type_pc);
436 case "phone":
437 return context.getString(R.string.type_phone);
438 case "tablet":
439 return context.getString(R.string.type_tablet);
440 case "web":
441 return context.getString(R.string.type_web);
442 case "console":
443 return context.getString(R.string.type_console);
444 default:
445 return type;
446 }
447 }
448
449 public static boolean showIconsInPopup(PopupMenu attachFilePopup) {
450 try {
451 Field field = attachFilePopup.getClass().getDeclaredField("mPopup");
452 field.setAccessible(true);
453 Object menuPopupHelper = field.get(attachFilePopup);
454 Class<?> cls = Class.forName("com.android.internal.view.menu.MenuPopupHelper");
455 Method method = cls.getDeclaredMethod("setForceShowIcon", new Class[]{boolean.class});
456 method.setAccessible(true);
457 method.invoke(menuPopupHelper, new Object[]{true});
458 return true;
459 } catch (Exception e) {
460 return false;
461 }
462 }
463}