1package eu.siacs.conversations.utils;
2
3import android.content.Context;
4import android.content.res.ColorStateList;
5import android.text.SpannableStringBuilder;
6import android.text.format.DateFormat;
7import android.text.format.DateUtils;
8import android.util.Pair;
9import android.widget.TextView;
10
11import androidx.annotation.ColorInt;
12import androidx.annotation.ColorRes;
13import androidx.annotation.StringRes;
14import androidx.core.content.ContextCompat;
15
16import com.google.android.material.color.MaterialColors;
17import com.google.common.base.Strings;
18
19import java.util.Arrays;
20import java.util.Calendar;
21import java.util.Date;
22import java.util.List;
23import java.util.Locale;
24
25import eu.siacs.conversations.Config;
26import eu.siacs.conversations.R;
27import eu.siacs.conversations.crypto.axolotl.AxolotlService;
28import eu.siacs.conversations.entities.Account;
29import eu.siacs.conversations.entities.Contact;
30import eu.siacs.conversations.entities.Conversation;
31import eu.siacs.conversations.entities.Conversational;
32import eu.siacs.conversations.entities.Message;
33import eu.siacs.conversations.entities.MucOptions;
34import eu.siacs.conversations.entities.Presence;
35import eu.siacs.conversations.entities.RtpSessionStatus;
36import eu.siacs.conversations.entities.Transferable;
37import eu.siacs.conversations.ui.util.QuoteHelper;
38import eu.siacs.conversations.worker.ExportBackupWorker;
39import eu.siacs.conversations.xmpp.Jid;
40
41public class UIHelper {
42
43 private static final List<String> LOCATION_QUESTIONS = Arrays.asList(
44 "where are you", //en
45 "where are you now", //en
46 "where are you right now", //en
47 "whats your 20", //en
48 "what is your 20", //en
49 "what's your 20", //en
50 "whats your twenty", //en
51 "what is your twenty", //en
52 "what's your twenty", //en
53 "wo bist du", //de
54 "wo bist du jetzt", //de
55 "wo bist du gerade", //de
56 "wo seid ihr", //de
57 "wo seid ihr jetzt", //de
58 "wo seid ihr gerade", //de
59 "dónde estás", //es
60 "donde estas" //es
61 );
62
63 private static final List<Character> PUNCTIONATION = Arrays.asList('.', ',', '?', '!', ';', ':');
64
65 private static final int SHORT_DATE_FLAGS = DateUtils.FORMAT_SHOW_DATE
66 | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
67 private static final int FULL_DATE_FLAGS = DateUtils.FORMAT_SHOW_TIME
68 | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE;
69
70 public static String readableTimeDifference(Context context, long time) {
71 return readableTimeDifference(context, time, false);
72 }
73
74 public static String readableTimeDifferenceFull(Context context, long time) {
75 return readableTimeDifference(context, time, true);
76 }
77
78 private static String readableTimeDifference(Context context, long time,
79 boolean fullDate) {
80 if (time == 0) {
81 return context.getString(R.string.just_now);
82 }
83 Date date = new Date(time);
84 long difference = (System.currentTimeMillis() - time) / 1000;
85 if (difference < 60) {
86 return context.getString(R.string.just_now);
87 } else if (difference < 60 * 2) {
88 return context.getString(R.string.minute_ago);
89 } else if (difference < 60 * 15) {
90 return context.getString(R.string.minutes_ago, Math.round(difference / 60.0));
91 } else if (today(date)) {
92 java.text.DateFormat df = DateFormat.getTimeFormat(context);
93 return df.format(date);
94 } else {
95 if (fullDate) {
96 return DateUtils.formatDateTime(context, date.getTime(),
97 FULL_DATE_FLAGS);
98 } else {
99 return DateUtils.formatDateTime(context, date.getTime(),
100 SHORT_DATE_FLAGS);
101 }
102 }
103 }
104
105 private static boolean today(Date date) {
106 return sameDay(date, new Date(System.currentTimeMillis()));
107 }
108
109 public static boolean today(long date) {
110 return sameDay(date, System.currentTimeMillis());
111 }
112
113 public static boolean yesterday(long date) {
114 Calendar cal1 = Calendar.getInstance();
115 Calendar cal2 = Calendar.getInstance();
116 cal1.add(Calendar.DAY_OF_YEAR, -1);
117 cal2.setTime(new Date(date));
118 return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
119 && cal1.get(Calendar.DAY_OF_YEAR) == cal2
120 .get(Calendar.DAY_OF_YEAR);
121 }
122
123 public static boolean sameDay(long a, long b) {
124 return sameDay(new Date(a), new Date(b));
125 }
126
127 private static boolean sameDay(Date a, Date b) {
128 Calendar cal1 = Calendar.getInstance();
129 Calendar cal2 = Calendar.getInstance();
130 cal1.setTime(a);
131 cal2.setTime(b);
132 return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
133 && cal1.get(Calendar.DAY_OF_YEAR) == cal2
134 .get(Calendar.DAY_OF_YEAR);
135 }
136
137 public static String lastseen(Context context, boolean active, long time) {
138 long difference = (System.currentTimeMillis() - time) / 1000;
139 if (active) {
140 return context.getString(R.string.online_right_now);
141 } else if (difference < 60) {
142 return context.getString(R.string.last_seen_now);
143 } else if (difference < 60 * 2) {
144 return context.getString(R.string.last_seen_min);
145 } else if (difference < 60 * 60) {
146 return context.getString(R.string.last_seen_mins, Math.round(difference / 60.0));
147 } else if (difference < 60 * 60 * 2) {
148 return context.getString(R.string.last_seen_hour);
149 } else if (difference < 60 * 60 * 24) {
150 return context.getString(R.string.last_seen_hours,
151 Math.round(difference / (60.0 * 60.0)));
152 } else if (difference < 60 * 60 * 48) {
153 return context.getString(R.string.last_seen_day);
154 } else {
155 return context.getString(R.string.last_seen_days,
156 Math.round(difference / (60.0 * 60.0 * 24.0)));
157 }
158 }
159
160
161 public static int getColorForName(final String name) {
162 return XEP0392Helper.rgbFromNick(name);
163 }
164
165
166 public static Pair<CharSequence, Boolean> getMessagePreview(final Context context, final Message message) {
167 return getMessagePreview(context, message, 0);
168 }
169
170 public static Pair<CharSequence, Boolean> getMessagePreview(final Context context, final Message message, @ColorInt int textColor) {
171 final Transferable d = message.getTransferable();
172 if (d != null) {
173 switch (d.getStatus()) {
174 case Transferable.STATUS_CHECKING:
175 return new Pair<>(context.getString(R.string.checking_x,
176 getFileDescriptionString(context, message)), true);
177 case Transferable.STATUS_DOWNLOADING:
178 return new Pair<>(context.getString(R.string.receiving_x_file,
179 getFileDescriptionString(context, message),
180 d.getProgress()), true);
181 case Transferable.STATUS_OFFER:
182 case Transferable.STATUS_OFFER_CHECK_FILESIZE:
183 return new Pair<>(context.getString(R.string.x_file_offered_for_download,
184 getFileDescriptionString(context, message)), true);
185 case Transferable.STATUS_FAILED:
186 return new Pair<>(context.getString(R.string.file_transmission_failed), true);
187 case Transferable.STATUS_CANCELLED:
188 return new Pair<>(context.getString(R.string.file_transmission_cancelled), true);
189 case Transferable.STATUS_UPLOADING:
190 if (message.getStatus() == Message.STATUS_OFFERED) {
191 return new Pair<>(context.getString(R.string.offering_x_file,
192 getFileDescriptionString(context, message)), true);
193 } else {
194 return new Pair<>(context.getString(R.string.sending_x_file,
195 getFileDescriptionString(context, message)), true);
196 }
197 default:
198 return new Pair<>("", false);
199 }
200 } else if (message.isFileOrImage() && message.isDeleted()) {
201 return new Pair<>(context.getString(R.string.file_deleted), true);
202 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
203 return new Pair<>(context.getString(R.string.pgp_message), true);
204 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
205 return new Pair<>(context.getString(R.string.decryption_failed), true);
206 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
207 return new Pair<>(context.getString(R.string.not_encrypted_for_this_device), true);
208 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
209 return new Pair<>(context.getString(R.string.omemo_decryption_failed), true);
210 } else if (message.isFileOrImage()) {
211 return new Pair<>(getFileDescriptionString(context, message), true);
212 } else if (message.getType() == Message.TYPE_RTP_SESSION) {
213 RtpSessionStatus rtpSessionStatus = RtpSessionStatus.of(message.getBody());
214 final boolean received = message.getStatus() == Message.STATUS_RECEIVED;
215 if (!rtpSessionStatus.successful && received) {
216 return new Pair<>(context.getString(R.string.missed_call), true);
217 } else {
218 return new Pair<>(context.getString(received ? R.string.incoming_call : R.string.outgoing_call), true);
219 }
220 } else {
221 final String body = MessageUtils.filterLtrRtl(message.getBody());
222 if (body.startsWith(Message.ME_COMMAND)) {
223 return new Pair<>(body.replaceAll("^" + Message.ME_COMMAND,
224 UIHelper.getMessageDisplayName(message) + " "), false);
225 } else if (message.isGeoUri()) {
226 return new Pair<>(context.getString(R.string.location), true);
227 } else if (message.treatAsDownloadable() || MessageUtils.unInitiatedButKnownSize(message)) {
228 return new Pair<>(context.getString(R.string.x_file_offered_for_download,
229 getFileDescriptionString(context, message)), true);
230 } else {
231 SpannableStringBuilder styledBody = new SpannableStringBuilder(body);
232 if (textColor != 0) {
233 StylingHelper.format(styledBody, 0, styledBody.length() - 1, textColor);
234 }
235 SpannableStringBuilder builder = new SpannableStringBuilder();
236 for (CharSequence l : CharSequenceUtils.split(styledBody, '\n')) {
237 if (l.length() > 0) {
238 if (l.toString().equals("```")) {
239 continue;
240 }
241 char first = l.charAt(0);
242 if ((!QuoteHelper.isPositionQuoteStart(l, 0))) {
243 CharSequence line = CharSequenceUtils.trim(l);
244 if (line.length() == 0) {
245 continue;
246 }
247 char last = line.charAt(line.length() - 1);
248 if (builder.length() != 0) {
249 builder.append(' ');
250 }
251 builder.append(line);
252 if (!PUNCTIONATION.contains(last)) {
253 break;
254 }
255 }
256 }
257 }
258 if (builder.length() == 0) {
259 builder.append(body.trim());
260 }
261 return new Pair<>(builder, false);
262 }
263 }
264 }
265
266 public static boolean isLastLineQuote(String body) {
267 if (body.endsWith("\n")) {
268 return false;
269 }
270 String[] lines = body.split("\n");
271 if (lines.length == 0) {
272 return false;
273 }
274 String line = lines[lines.length - 1];
275 if (line.isEmpty()) {
276 return false;
277 }
278 char first = line.charAt(0);
279 return first == '>' && isPositionFollowedByQuoteableCharacter(line, 0) || first == '\u00bb';
280 }
281
282 public static CharSequence shorten(CharSequence input) {
283 return input.length() > 256 ? StylingHelper.subSequence(input, 0, 256) : input;
284 }
285
286 public static boolean isPositionPrecededByBodyStart(CharSequence body, int pos){
287 // true if not a single linebreak before current position
288 for (int i = pos - 1; i >= 0; i--){
289 if (body.charAt(i) != ' '){
290 return false;
291 }
292 }
293 return true;
294 }
295
296 public static boolean isPositionPrecededByLineStart(CharSequence body, int pos){
297 if (isPositionPrecededByBodyStart(body, pos)){
298 return true;
299 }
300 return body.charAt(pos - 1) == '\n';
301 }
302
303 public static boolean isPositionFollowedByQuoteableCharacter(CharSequence body, int pos) {
304 return !isPositionFollowedByNumber(body, pos)
305 && !isPositionFollowedByEmoticon(body, pos)
306 && !isPositionFollowedByEquals(body, pos);
307 }
308
309 private static boolean isPositionFollowedByNumber(CharSequence body, int pos) {
310 boolean previousWasNumber = false;
311 for (int i = pos + 1; i < body.length(); i++) {
312 char c = body.charAt(i);
313 if (Character.isDigit(body.charAt(i))) {
314 previousWasNumber = true;
315 } else if (previousWasNumber && (c == '.' || c == ',')) {
316 previousWasNumber = false;
317 } else {
318 return (Character.isWhitespace(c) || c == '%' || c == '+') && previousWasNumber;
319 }
320 }
321 return previousWasNumber;
322 }
323
324 private static boolean isPositionFollowedByEquals(CharSequence body, int pos) {
325 return body.length() > pos + 1 && body.charAt(pos + 1) == '=';
326 }
327
328 private static boolean isPositionFollowedByEmoticon(CharSequence body, int pos) {
329 if (body.length() <= pos + 1) {
330 return false;
331 } else {
332 final char first = body.charAt(pos + 1);
333 return first == ';'
334 || first == ':'
335 || first == '.' // do not quote >.< (but >>.<)
336 || closingBeforeWhitespace(body, pos + 1);
337 }
338 }
339
340 private static boolean closingBeforeWhitespace(CharSequence body, int pos) {
341 for (int i = pos; i < body.length(); ++i) {
342 final char c = body.charAt(i);
343 if (Character.isWhitespace(c)) {
344 return false;
345 } else if (QuoteHelper.isPositionQuoteCharacter(body, pos) || QuoteHelper.isPositionQuoteEndCharacter(body, pos)) {
346 return body.length() == i + 1 || Character.isWhitespace(body.charAt(i + 1));
347 }
348 }
349 return false;
350 }
351
352 public static String getDisplayName(MucOptions.User user) {
353 Contact contact = user.getContact();
354 if (contact != null) {
355 return contact.getDisplayName();
356 } else {
357 final String name = user.getName();
358 if (name != null) {
359 return name;
360 }
361 final Jid realJid = user.getRealJid();
362 if (realJid != null) {
363 return JidHelper.localPartOrFallback(realJid);
364 }
365 return null;
366 }
367 }
368
369 public static String concatNames(List<MucOptions.User> users) {
370 return concatNames(users, users.size());
371 }
372
373 public static String concatNames(List<MucOptions.User> users, int max) {
374 StringBuilder builder = new StringBuilder();
375 final boolean shortNames = users.size() >= 3;
376 for (int i = 0; i < Math.min(users.size(), max); ++i) {
377 if (builder.length() != 0) {
378 builder.append(", ");
379 }
380 final String name = UIHelper.getDisplayName(users.get(i));
381 if (name != null) {
382 builder.append(shortNames ? name.split("\\s+")[0] : name);
383 }
384 }
385 return builder.toString();
386 }
387
388 public static String getFileDescriptionString(final Context context, final Message message) {
389 final String mime = message.getMimeType();
390 if (Strings.isNullOrEmpty(mime)) {
391 return context.getString(R.string.file);
392 } else if (MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime)) {
393 return context.getString(R.string.multimedia_file);
394 } else if (mime.equals("audio/x-m4b")) {
395 return context.getString(R.string.audiobook);
396 } else if (mime.startsWith("audio/")) {
397 return context.getString(R.string.audio);
398 } else if (mime.startsWith("video/")) {
399 return context.getString(R.string.video);
400 } else if (mime.equals("image/gif")) {
401 return context.getString(R.string.gif);
402 } else if (mime.equals("image/svg+xml")) {
403 return context.getString(R.string.vector_graphic);
404 } else if (mime.startsWith("image/") || message.getType() == Message.TYPE_IMAGE) {
405 return context.getString(R.string.image);
406 } else if (mime.contains("pdf")) {
407 return context.getString(R.string.pdf_document);
408 } else if (mime.equals("application/vnd.android.package-archive")) {
409 return context.getString(R.string.apk);
410 } else if (mime.equals(ExportBackupWorker.MIME_TYPE)) {
411 return context.getString(R.string.conversations_backup);
412 } else if (mime.contains("vcard")) {
413 return context.getString(R.string.vcard);
414 } else if (mime.equals("text/x-vcalendar") || mime.equals("text/calendar")) {
415 return context.getString(R.string.event);
416 } else if (mime.equals("application/epub+zip") || mime.equals("application/vnd.amazon.mobi8-ebook")) {
417 return context.getString(R.string.ebook);
418 } else if (mime.equals("application/gpx+xml")) {
419 return context.getString(R.string.gpx_track);
420 } else if (mime.equals("text/plain")) {
421 return context.getString(R.string.plain_text_document);
422 } else {
423 return mime;
424 }
425 }
426
427 public static String getMessageDisplayName(final Message message) {
428 final Conversational conversation = message.getConversation();
429 if (message.getStatus() == Message.STATUS_RECEIVED) {
430 final Contact contact = message.getContact();
431 if (conversation.getMode() == Conversation.MODE_MULTI) {
432 if (contact != null) {
433 return contact.getDisplayName();
434 } else {
435 return getDisplayedMucCounterpart(message.getCounterpart());
436 }
437 } else {
438 return contact != null ? contact.getDisplayName() : "";
439 }
440 } else {
441 if (conversation instanceof Conversation && conversation.getMode() == Conversation.MODE_MULTI) {
442 return ((Conversation) conversation).getMucOptions().getSelf().getName();
443 } else {
444 final Account account = conversation.getAccount();
445 final Jid jid = account.getJid();
446 final String displayName = account.getDisplayName();
447 if (Strings.isNullOrEmpty(displayName)) {
448 return jid.getLocal() != null ? jid.getLocal() : jid.getDomain().toString();
449 } else {
450 return displayName;
451 }
452
453 }
454 }
455 }
456
457 public static String getMessageHint(final Context context,final Conversation conversation) {
458 return switch (conversation.getNextEncryption()) {
459 case Message.ENCRYPTION_NONE -> {
460 if (Config.multipleEncryptionChoices()) {
461 yield context.getString(R.string.send_unencrypted_message);
462 } else {
463 yield context.getString(R.string.send_message_to_x, conversation.getName());
464 }
465 }
466 case Message.ENCRYPTION_AXOLOTL -> {
467 final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
468 if (axolotlService != null && axolotlService.trustedSessionVerified(conversation)) {
469 yield context.getString(R.string.send_omemo_x509_message);
470 } else {
471 yield context.getString(R.string.send_encrypted_message);
472 }
473 }
474 default -> context.getString(R.string.send_encrypted_message);
475 };
476 }
477
478 public static String getDisplayedMucCounterpart(final Jid counterpart) {
479 if (counterpart == null) {
480 return "";
481 } else if (!counterpart.isBareJid()) {
482 return counterpart.getResource().trim();
483 } else {
484 return counterpart.toString().trim();
485 }
486 }
487
488 public static boolean receivedLocationQuestion(final Message message) {
489 if (message == null
490 || message.getStatus() != Message.STATUS_RECEIVED
491 || message.getType() != Message.TYPE_TEXT) {
492 return false;
493 }
494 final String body = Strings.nullToEmpty(message.getBody())
495 .trim()
496 .toLowerCase(Locale.getDefault())
497 .replace("?", "").replace("¿", "");
498 return LOCATION_QUESTIONS.contains(body);
499 }
500
501 public static void setStatus(final TextView textView, Presence.Status status) {
502 final @StringRes int text;
503 final @ColorRes int color =
504 switch (status) {
505 case CHAT -> {
506 text = R.string.presence_chat;
507 yield R.color.green_800;
508 }
509 case ONLINE -> {
510 text = R.string.presence_online;
511 yield R.color.green_800;
512 }
513 case AWAY -> {
514 text = R.string.presence_away;
515 yield R.color.amber_800;
516 }
517 case XA -> {
518 text = R.string.presence_xa;
519 yield R.color.orange_800;
520 }
521 case DND -> {
522 text = R.string.presence_dnd;
523 yield R.color.red_800;
524 }
525 default -> throw new IllegalStateException();
526 };
527 textView.setText(text);
528 textView.setBackgroundTintList(
529 ColorStateList.valueOf(
530 MaterialColors.harmonizeWithPrimary(
531 textView.getContext(),
532 ContextCompat.getColor(textView.getContext(), color))));
533 }
534
535 public static String filesizeToString(long size) {
536 if (size > (1.5 * 1024 * 1024)) {
537 return Math.round(size * 1f / (1024 * 1024)) + " MiB";
538 } else if (size >= 1024) {
539 return Math.round(size * 1f / 1024) + " KiB";
540 } else {
541 return size + " B";
542 }
543 }
544}