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 }
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 isPositionFollowedByEmoticon(CharSequence body, int pos) {
253 if (body.length() <= pos +1) {
254 return false;
255 } else {
256 final char first = body.charAt(pos +1);
257 return first == ';'
258 || first == ':'
259 || smallerThanBeforeWhitespace(body,pos+1);
260 }
261 }
262
263 private static boolean smallerThanBeforeWhitespace(CharSequence body, int pos) {
264 for(int i = pos; i < body.length(); ++i) {
265 final char c = body.charAt(i);
266 if (Character.isWhitespace(c)) {
267 return false;
268 } else if (c == '<') {
269 return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
270 }
271 }
272 return false;
273 }
274
275 public static boolean isPositionFollowedByQuote(CharSequence body, int pos) {
276 if (body.length() <= pos + 1 || Character.isWhitespace(body.charAt(pos+1))) {
277 return false;
278 }
279 boolean previousWasWhitespace = false;
280 for (int i = pos +1; i < body.length(); i++) {
281 char c = body.charAt(i);
282 if (c == '\n' || c == '»') {
283 return false;
284 } else if (c == '«' && !previousWasWhitespace) {
285 return true;
286 } else {
287 previousWasWhitespace = Character.isWhitespace(c);
288 }
289 }
290 return false;
291 }
292
293 public static String getDisplayName(MucOptions.User user) {
294 Contact contact = user.getContact();
295 if (contact != null) {
296 return contact.getDisplayName();
297 } else {
298 return user.getName();
299 }
300 }
301
302 public static String getFileDescriptionString(final Context context, final Message message) {
303 if (message.getType() == Message.TYPE_IMAGE) {
304 return context.getString(R.string.image);
305 }
306 final String mime = message.getMimeType();
307 if (mime == null) {
308 return context.getString(R.string.file);
309 } else if (mime.startsWith("audio/")) {
310 return context.getString(R.string.audio);
311 } else if(mime.startsWith("video/")) {
312 return context.getString(R.string.video);
313 } else if (mime.startsWith("image/")) {
314 return context.getString(R.string.image);
315 } else if (mime.contains("pdf")) {
316 return context.getString(R.string.pdf_document) ;
317 } else if (mime.contains("application/vnd.android.package-archive")) {
318 return context.getString(R.string.apk) ;
319 } else if (mime.contains("vcard")) {
320 return context.getString(R.string.vcard) ;
321 } else {
322 return mime;
323 }
324 }
325
326 public static String getMessageDisplayName(final Message message) {
327 final Conversation conversation = message.getConversation();
328 if (message.getStatus() == Message.STATUS_RECEIVED) {
329 final Contact contact = message.getContact();
330 if (conversation.getMode() == Conversation.MODE_MULTI) {
331 if (contact != null) {
332 return contact.getDisplayName();
333 } else {
334 return getDisplayedMucCounterpart(message.getCounterpart());
335 }
336 } else {
337 return contact != null ? contact.getDisplayName() : "";
338 }
339 } else {
340 if (conversation.getMode() == Conversation.MODE_MULTI) {
341 return conversation.getMucOptions().getSelf().getName();
342 } else {
343 final Jid jid = conversation.getAccount().getJid();
344 return jid.hasLocalpart() ? jid.getLocalpart() : jid.toDomainJid().toString();
345 }
346 }
347 }
348
349 public static String getMessageHint(Context context, Conversation conversation) {
350 switch (conversation.getNextEncryption()) {
351 case Message.ENCRYPTION_NONE:
352 if (Config.multipleEncryptionChoices()) {
353 return context.getString(R.string.send_unencrypted_message);
354 } else {
355 return context.getString(R.string.send_message_to_x,conversation.getName());
356 }
357 case Message.ENCRYPTION_OTR:
358 return context.getString(R.string.send_otr_message);
359 case Message.ENCRYPTION_AXOLOTL:
360 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
361 if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
362 return context.getString(R.string.send_omemo_x509_message);
363 } else {
364 return context.getString(R.string.send_omemo_message);
365 }
366 case Message.ENCRYPTION_PGP:
367 return context.getString(R.string.send_pgp_message);
368 default:
369 return "";
370 }
371 }
372
373 public static String getDisplayedMucCounterpart(final Jid counterpart) {
374 if (counterpart==null) {
375 return "";
376 } else if (!counterpart.isBareJid()) {
377 return counterpart.getResourcepart().trim();
378 } else {
379 return counterpart.toString().trim();
380 }
381 }
382
383 public static boolean receivedLocationQuestion(Message message) {
384 if (message == null
385 || message.getStatus() != Message.STATUS_RECEIVED
386 || message.getType() != Message.TYPE_TEXT) {
387 return false;
388 }
389 String body = message.getBody() == null ? null : message.getBody().trim().toLowerCase(Locale.getDefault());
390 body = body.replace("?","").replace("¿","");
391 return LOCATION_QUESTIONS.contains(body);
392 }
393
394 public static ListItem.Tag getTagForStatus(Context context, Presence.Status status) {
395 switch (status) {
396 case CHAT:
397 return new ListItem.Tag(context.getString(R.string.presence_chat), 0xff259b24);
398 case AWAY:
399 return new ListItem.Tag(context.getString(R.string.presence_away), 0xffff9800);
400 case XA:
401 return new ListItem.Tag(context.getString(R.string.presence_xa), 0xfff44336);
402 case DND:
403 return new ListItem.Tag(context.getString(R.string.presence_dnd), 0xfff44336);
404 default:
405 return new ListItem.Tag(context.getString(R.string.presence_online), 0xff259b24);
406 }
407 }
408
409 public static String tranlasteType(Context context, String type) {
410 switch (type.toLowerCase()) {
411 case "pc":
412 return context.getString(R.string.type_pc);
413 case "phone":
414 return context.getString(R.string.type_phone);
415 case "tablet":
416 return context.getString(R.string.type_tablet);
417 case "web":
418 return context.getString(R.string.type_web);
419 case "console":
420 return context.getString(R.string.type_console);
421 default:
422 return type;
423 }
424 }
425
426 public static boolean showIconsInPopup(PopupMenu attachFilePopup) {
427 try {
428 Field field = attachFilePopup.getClass().getDeclaredField("mPopup");
429 field.setAccessible(true);
430 Object menuPopupHelper = field.get(attachFilePopup);
431 Class<?> cls = Class.forName("com.android.internal.view.menu.MenuPopupHelper");
432 Method method = cls.getDeclaredMethod("setForceShowIcon", new Class[]{boolean.class});
433 method.setAccessible(true);
434 method.invoke(menuPopupHelper, new Object[]{true});
435 return true;
436 } catch (Exception e) {
437 return false;
438 }
439 }
440}