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