1package eu.siacs.conversations.utils;
2
3import java.io.FileNotFoundException;
4import java.util.ArrayList;
5import java.util.Calendar;
6import java.util.Date;
7import java.util.List;
8import java.util.Locale;
9import java.util.regex.Pattern;
10import java.util.regex.Matcher;
11
12import eu.siacs.conversations.R;
13import eu.siacs.conversations.entities.Account;
14import eu.siacs.conversations.entities.Contact;
15import eu.siacs.conversations.entities.Conversation;
16import eu.siacs.conversations.entities.Message;
17import eu.siacs.conversations.entities.MucOptions.User;
18import eu.siacs.conversations.ui.ConversationActivity;
19import eu.siacs.conversations.ui.ManageAccountActivity;
20import android.app.Activity;
21import android.app.AlertDialog;
22import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.DialogInterface.OnClickListener;
28import android.content.Intent;
29import android.content.SharedPreferences;
30import android.graphics.Bitmap;
31import android.graphics.BitmapFactory;
32import android.graphics.Canvas;
33import android.graphics.Paint;
34import android.graphics.Rect;
35import android.graphics.Typeface;
36import android.net.Uri;
37import android.preference.PreferenceManager;
38import android.provider.ContactsContract.Contacts;
39import android.support.v4.app.NotificationCompat;
40import android.support.v4.app.TaskStackBuilder;
41import android.text.format.DateFormat;
42import android.text.format.DateUtils;
43import android.text.Html;
44import android.util.DisplayMetrics;
45import android.view.LayoutInflater;
46import android.view.View;
47import android.widget.QuickContactBadge;
48import android.widget.TextView;
49
50public class UIHelper {
51 private static final int BG_COLOR = 0xFF181818;
52 private static final int FG_COLOR = 0xFFFAFAFA;
53 private static final int TRANSPARENT = 0x00000000;
54 private static final int DATE_NO_YEAR_FLAGS = DateUtils.FORMAT_SHOW_DATE
55 | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
56
57 public static String readableTimeDifference(Context context, long time) {
58 if (time == 0) {
59 return context.getString(R.string.just_now);
60 }
61 Date date = new Date(time);
62 long difference = (System.currentTimeMillis() - time) / 1000;
63 if (difference < 60) {
64 return context.getString(R.string.just_now);
65 } else if (difference < 60 * 2) {
66 return context.getString(R.string.minute_ago);
67 } else if (difference < 60 * 15) {
68 return context.getString(R.string.minutes_ago,
69 Math.round(difference / 60.0));
70 } else if (today(date) || difference < 6 * 60 * 60) {
71 java.text.DateFormat df = DateFormat.getTimeFormat(context);
72 return df.format(date);
73 } else {
74 return DateUtils.formatDateTime(context, date.getTime(),
75 DATE_NO_YEAR_FLAGS);
76 }
77 }
78
79 private static boolean today(Date date) {
80 Calendar cal1 = Calendar.getInstance();
81 Calendar cal2 = Calendar.getInstance();
82 cal1.setTime(date);
83 cal2.setTimeInMillis(System.currentTimeMillis());
84 return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
85 && cal1.get(Calendar.DAY_OF_YEAR) == cal2
86 .get(Calendar.DAY_OF_YEAR);
87 }
88
89 public static String lastseen(Context context, long time) {
90 if (time == 0) {
91 return context.getString(R.string.never_seen);
92 }
93 long difference = (System.currentTimeMillis() - time) / 1000;
94 if (difference < 60) {
95 return context.getString(R.string.last_seen_now);
96 } else if (difference < 60 * 2) {
97 return context.getString(R.string.last_seen_min);
98 } else if (difference < 60 * 60) {
99 return context.getString(R.string.last_seen_mins,
100 Math.round(difference / 60.0));
101 } else if (difference < 60 * 60 * 2) {
102 return context.getString(R.string.last_seen_hour);
103 } else if (difference < 60 * 60 * 24) {
104 return context.getString(R.string.last_seen_hours,
105 Math.round(difference / (60.0 * 60.0)));
106 } else if (difference < 60 * 60 * 48) {
107 return context.getString(R.string.last_seen_day);
108 } else {
109 return context.getString(R.string.last_seen_days,
110 Math.round(difference / (60.0 * 60.0 * 24.0)));
111 }
112 }
113
114 public static int getRealPx(int dp, Context context) {
115 final DisplayMetrics metrics = context.getResources()
116 .getDisplayMetrics();
117 return ((int) (dp * metrics.density));
118 }
119
120 private static int getNameColor(String name) {
121 /*
122 * int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713,
123 * 0xFFe92727 };
124 */
125 int holoColors[] = { 0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5,
126 0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722,
127 0xFF795548, 0xFF607d8b };
128 return holoColors[(int) ((name.hashCode() & 0xffffffffl) % holoColors.length)];
129 }
130
131 private static void drawTile(Canvas canvas, String letter, int tileColor,
132 int textColor, int left, int top, int right, int bottom) {
133 Paint tilePaint = new Paint(), textPaint = new Paint();
134 tilePaint.setColor(tileColor);
135 textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
136 textPaint.setColor(textColor);
137 textPaint.setTypeface(Typeface.create("sans-serif-light",
138 Typeface.NORMAL));
139 textPaint.setTextSize((float) ((right - left) * 0.8));
140 Rect rect = new Rect();
141
142 canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
143 textPaint.getTextBounds(letter, 0, 1, rect);
144 float width = textPaint.measureText(letter);
145 canvas.drawText(letter, (right + left) / 2 - width / 2, (top + bottom)
146 / 2 + rect.height() / 2, textPaint);
147 }
148
149 private static Bitmap getUnknownContactPicture(String[] names, int size,
150 int bgColor, int fgColor) {
151 int tiles = (names.length > 4) ? 4 : (names.length < 1) ? 1
152 : names.length;
153 Bitmap bitmap = Bitmap
154 .createBitmap(size, size, Bitmap.Config.ARGB_8888);
155 Canvas canvas = new Canvas(bitmap);
156
157 String[] letters = new String[tiles];
158 int[] colors = new int[tiles];
159 if (names.length < 1) {
160 letters[0] = "?";
161 colors[0] = 0xFFe92727;
162 } else {
163 for (int i = 0; i < tiles; ++i) {
164 letters[i] = (names[i].length() > 0) ? names[i].substring(0, 1)
165 .toUpperCase(Locale.US) : " ";
166 colors[i] = getNameColor(names[i]);
167 }
168
169 if (names.length > 4) {
170 letters[3] = "\u2026"; // Unicode ellipsis
171 colors[3] = 0xFF202020;
172 }
173 }
174
175 bitmap.eraseColor(bgColor);
176
177 switch (tiles) {
178 case 1:
179 drawTile(canvas, letters[0], colors[0], fgColor, 0, 0, size, size);
180 break;
181
182 case 2:
183 drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
184 size / 2 - 1, size);
185 drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
186 size, size);
187 break;
188
189 case 3:
190 drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
191 size / 2 - 1, size);
192 drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
193 size, size / 2 - 1);
194 drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1,
195 size / 2 + 1, size, size);
196 break;
197
198 case 4:
199 drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
200 size / 2 - 1, size / 2 - 1);
201 drawTile(canvas, letters[1], colors[1], fgColor, 0, size / 2 + 1,
202 size / 2 - 1, size);
203 drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1, 0,
204 size, size / 2 - 1);
205 drawTile(canvas, letters[3], colors[3], fgColor, size / 2 + 1,
206 size / 2 + 1, size, size);
207 break;
208 }
209
210 return bitmap;
211 }
212
213 private static Bitmap getMucContactPicture(Conversation conversation,
214 int size, int bgColor, int fgColor) {
215 List<User> members = conversation.getMucOptions().getUsers();
216 if (members.size() == 0) {
217 return getUnknownContactPicture(
218 new String[] { conversation.getName() }, size, bgColor,
219 fgColor);
220 }
221 ArrayList<String> names = new ArrayList<String>();
222 names.add(conversation.getMucOptions().getActualNick());
223 for (User user : members) {
224 names.add(user.getName());
225 if (names.size() > 4) {
226 break;
227 }
228 }
229 String[] mArrayNames = new String[names.size()];
230 names.toArray(mArrayNames);
231 return getUnknownContactPicture(mArrayNames, size, bgColor, fgColor);
232 }
233
234 public static Bitmap getContactPicture(Conversation conversation,
235 int dpSize, Context context, boolean notification) {
236 if (conversation.getMode() == Conversation.MODE_SINGLE) {
237 return getContactPicture(conversation.getContact(), dpSize,
238 context, notification);
239 } else {
240 int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
241 : UIHelper.TRANSPARENT;
242
243 return getMucContactPicture(conversation,
244 getRealPx(dpSize, context), bgColor, fgColor);
245 }
246 }
247
248 public static Bitmap getContactPicture(Contact contact, int dpSize,
249 Context context, boolean notification) {
250 String uri = contact.getProfilePhoto();
251 if (uri == null) {
252 return getContactPicture(contact.getDisplayName(), dpSize, context,
253 notification);
254 }
255 try {
256 Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
257 .openInputStream(Uri.parse(uri)));
258 return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
259 getRealPx(dpSize, context), false);
260 } catch (FileNotFoundException e) {
261 return getContactPicture(contact.getDisplayName(), dpSize, context,
262 notification);
263 }
264 }
265
266 public static Bitmap getContactPicture(String name, int dpSize,
267 Context context, boolean notification) {
268 int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
269 : UIHelper.TRANSPARENT;
270
271 return getUnknownContactPicture(new String[] { name },
272 getRealPx(dpSize, context), bgColor, fgColor);
273 }
274
275 public static void showErrorNotification(Context context,
276 List<Account> accounts) {
277 NotificationManager mNotificationManager = (NotificationManager) context
278 .getSystemService(Context.NOTIFICATION_SERVICE);
279 List<Account> accountsWproblems = new ArrayList<Account>();
280 for (Account account : accounts) {
281 if (account.hasErrorStatus()) {
282 accountsWproblems.add(account);
283 }
284 }
285 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
286 context);
287 if (accountsWproblems.size() == 0) {
288 mNotificationManager.cancel(1111);
289 return;
290 } else if (accountsWproblems.size() == 1) {
291 mBuilder.setContentTitle(context
292 .getString(R.string.problem_connecting_to_account));
293 mBuilder.setContentText(accountsWproblems.get(0).getJid());
294 } else {
295 mBuilder.setContentTitle(context
296 .getString(R.string.problem_connecting_to_accounts));
297 mBuilder.setContentText(context.getString(R.string.touch_to_fix));
298 }
299 mBuilder.setOngoing(true);
300 mBuilder.setLights(0xffffffff, 2000, 4000);
301 mBuilder.setSmallIcon(R.drawable.ic_notification);
302 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
303 stackBuilder.addParentStack(ConversationActivity.class);
304
305 Intent manageAccountsIntent = new Intent(context,
306 ManageAccountActivity.class);
307 stackBuilder.addNextIntent(manageAccountsIntent);
308
309 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
310 PendingIntent.FLAG_UPDATE_CURRENT);
311
312 mBuilder.setContentIntent(resultPendingIntent);
313 Notification notification = mBuilder.build();
314 mNotificationManager.notify(1111, notification);
315 }
316
317 private static Pattern generateNickHighlightPattern(String nick) {
318 // We expect a word boundary, i.e. space or start of string, followed by
319 // the
320 // nick (matched in case-insensitive manner), followed by optional
321 // punctuation (for example "bob: i disagree" or "how are you alice?"),
322 // followed by another word boundary.
323 return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
324 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
325 }
326
327 public static void updateNotification(Context context,
328 List<Conversation> conversations, Conversation currentCon,
329 boolean notify) {
330 NotificationManager mNotificationManager = (NotificationManager) context
331 .getSystemService(Context.NOTIFICATION_SERVICE);
332
333 SharedPreferences preferences = PreferenceManager
334 .getDefaultSharedPreferences(context);
335 boolean showNofifications = preferences.getBoolean("show_notification",
336 true);
337 boolean vibrate = preferences.getBoolean("vibrate_on_notification",
338 true);
339 boolean alwaysNotify = preferences.getBoolean(
340 "notify_in_conversation_when_highlighted", false);
341
342 if (!showNofifications) {
343 mNotificationManager.cancel(2342);
344 return;
345 }
346
347 String targetUuid = "";
348
349 if ((currentCon != null)
350 && (currentCon.getMode() == Conversation.MODE_MULTI)
351 && (!alwaysNotify) && notify) {
352 String nick = currentCon.getMucOptions().getActualNick();
353 Pattern highlight = generateNickHighlightPattern(nick);
354 Matcher m = highlight.matcher(currentCon.getLatestMessage()
355 .getBody());
356 notify = m.find();
357 }
358
359 List<Conversation> unread = new ArrayList<Conversation>();
360 for (Conversation conversation : conversations) {
361 if (conversation.getMode() == Conversation.MODE_MULTI) {
362 if ((!conversation.isRead())
363 && ((wasHighlighted(conversation) || (alwaysNotify)))) {
364 unread.add(conversation);
365 }
366 } else {
367 if (!conversation.isRead()) {
368 unread.add(conversation);
369 }
370 }
371 }
372 String ringtone = preferences.getString("notification_ringtone", null);
373
374 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
375 context);
376 if (unread.size() == 0) {
377 mNotificationManager.cancel(2342);
378 return;
379 } else if (unread.size() == 1) {
380 Conversation conversation = unread.get(0);
381 targetUuid = conversation.getUuid();
382 mBuilder.setLargeIcon(conversation.getImage(context, 64));
383 mBuilder.setContentTitle(conversation.getName());
384 if (notify) {
385 mBuilder.setTicker(conversation.getLatestMessage()
386 .getReadableBody(context));
387 }
388 StringBuilder bigText = new StringBuilder();
389 List<Message> messages = conversation.getMessages();
390 String firstLine = "";
391 for (int i = messages.size() - 1; i >= 0; --i) {
392 if (!messages.get(i).isRead()) {
393 if (i == messages.size() - 1) {
394 firstLine = messages.get(i).getReadableBody(context);
395 bigText.append(firstLine);
396 } else {
397 firstLine = messages.get(i).getReadableBody(context);
398 bigText.insert(0, firstLine + "\n");
399 }
400 } else {
401 break;
402 }
403 }
404 mBuilder.setContentText(firstLine);
405 mBuilder.setStyle(new NotificationCompat.BigTextStyle()
406 .bigText(bigText.toString()));
407 } else {
408 NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
409 style.setBigContentTitle(unread.size() + " "
410 + context.getString(R.string.unread_conversations));
411 StringBuilder names = new StringBuilder();
412 for (int i = 0; i < unread.size(); ++i) {
413 targetUuid = unread.get(i).getUuid();
414 if (i < unread.size() - 1) {
415 names.append(unread.get(i).getName() + ", ");
416 } else {
417 names.append(unread.get(i).getName());
418 }
419 style.addLine(Html.fromHtml("<b>"
420 + unread.get(i).getName()
421 + "</b> "
422 + unread.get(i).getLatestMessage()
423 .getReadableBody(context)));
424 }
425 mBuilder.setContentTitle(unread.size() + " "
426 + context.getString(R.string.unread_conversations));
427 mBuilder.setContentText(names.toString());
428 mBuilder.setStyle(style);
429 }
430 if ((currentCon != null) && (notify)) {
431 targetUuid = currentCon.getUuid();
432 }
433 if (unread.size() != 0) {
434 mBuilder.setSmallIcon(R.drawable.ic_notification);
435 if (notify) {
436 if (vibrate) {
437 int dat = 70;
438 long[] pattern = { 0, 3 * dat, dat, dat };
439 mBuilder.setVibrate(pattern);
440 }
441 mBuilder.setLights(0xffffffff, 2000, 4000);
442 if (ringtone != null) {
443 mBuilder.setSound(Uri.parse(ringtone));
444 }
445 }
446
447 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
448 stackBuilder.addParentStack(ConversationActivity.class);
449
450 Intent viewConversationIntent = new Intent(context,
451 ConversationActivity.class);
452 viewConversationIntent.setAction(Intent.ACTION_VIEW);
453 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
454 targetUuid);
455 viewConversationIntent
456 .setType(ConversationActivity.VIEW_CONVERSATION);
457
458 stackBuilder.addNextIntent(viewConversationIntent);
459
460 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
461 0, PendingIntent.FLAG_UPDATE_CURRENT);
462
463 mBuilder.setContentIntent(resultPendingIntent);
464 Notification notification = mBuilder.build();
465 mNotificationManager.notify(2342, notification);
466 }
467 }
468
469 private static boolean wasHighlighted(Conversation conversation) {
470 List<Message> messages = conversation.getMessages();
471 String nick = conversation.getMucOptions().getActualNick();
472 Pattern highlight = generateNickHighlightPattern(nick);
473 for (int i = messages.size() - 1; i >= 0; --i) {
474 if (messages.get(i).isRead()) {
475 break;
476 } else {
477 Matcher m = highlight.matcher(messages.get(i).getBody());
478 if (m.find()) {
479 return true;
480 }
481 }
482 }
483 return false;
484 }
485
486 public static void prepareContactBadge(final Activity activity,
487 QuickContactBadge badge, final Contact contact, Context context) {
488 if (contact.getSystemAccount() != null) {
489 String[] systemAccount = contact.getSystemAccount().split("#");
490 long id = Long.parseLong(systemAccount[0]);
491 badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
492 }
493 badge.setImageBitmap(contact.getImage(72, context));
494 }
495
496 public static AlertDialog getVerifyFingerprintDialog(
497 final ConversationActivity activity,
498 final Conversation conversation, final View msg) {
499 final Contact contact = conversation.getContact();
500 final Account account = conversation.getAccount();
501
502 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
503 builder.setTitle("Verify fingerprint");
504 LayoutInflater inflater = activity.getLayoutInflater();
505 View view = inflater.inflate(R.layout.dialog_verify_otr, null);
506 TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
507 TextView fingerprint = (TextView) view
508 .findViewById(R.id.verify_otr_fingerprint);
509 TextView yourprint = (TextView) view
510 .findViewById(R.id.verify_otr_yourprint);
511
512 jid.setText(contact.getJid());
513 fingerprint.setText(conversation.getOtrFingerprint());
514 yourprint.setText(account.getOtrFingerprint());
515 builder.setNegativeButton("Cancel", null);
516 builder.setPositiveButton("Verify", new OnClickListener() {
517
518 @Override
519 public void onClick(DialogInterface dialog, int which) {
520 contact.addOtrFingerprint(conversation.getOtrFingerprint());
521 msg.setVisibility(View.GONE);
522 activity.xmppConnectionService.syncRosterToDisk(account);
523 }
524 });
525 builder.setView(view);
526 return builder.create();
527 }
528
529 public static Bitmap getSelfContactPicture(Account account, int size,
530 boolean showPhoneSelfContactPicture, Context context) {
531 if (showPhoneSelfContactPicture) {
532 Uri selfiUri = PhoneHelper.getSefliUri(context);
533 if (selfiUri != null) {
534 try {
535 return BitmapFactory.decodeStream(context
536 .getContentResolver().openInputStream(selfiUri));
537 } catch (FileNotFoundException e) {
538 return getContactPicture(account.getJid(), size, context,
539 false);
540 }
541 }
542 return getContactPicture(account.getJid(), size, context, false);
543 } else {
544 return getContactPicture(account.getJid(), size, context, false);
545 }
546 }
547
548 private final static class EmoticonPattern {
549 Pattern pattern;
550 String replacement;
551
552 EmoticonPattern(String ascii, int unicode) {
553 this.pattern = Pattern.compile("(?<=(^|\\s))" + ascii
554 + "(?=(\\s|$))");
555 this.replacement = new String(new int[] { unicode, }, 0, 1);
556 }
557
558 String replaceAll(String body) {
559 return pattern.matcher(body).replaceAll(replacement);
560 }
561 }
562
563 private static final EmoticonPattern[] patterns = new EmoticonPattern[] {
564 new EmoticonPattern(":-?D", 0x1f600),
565 new EmoticonPattern("\\^\\^", 0x1f601),
566 new EmoticonPattern(":'D", 0x1f602),
567 new EmoticonPattern("\\]-?D", 0x1f608),
568 new EmoticonPattern(";-?\\)", 0x1f609),
569 new EmoticonPattern(":-?\\)", 0x1f60a),
570 new EmoticonPattern("[B8]-?\\)", 0x1f60e),
571 new EmoticonPattern(":-?\\|", 0x1f610),
572 new EmoticonPattern(":-?[/\\\\]", 0x1f615),
573 new EmoticonPattern(":-?\\*", 0x1f617),
574 new EmoticonPattern(":-?[Ppb]", 0x1f61b),
575 new EmoticonPattern(":-?\\(", 0x1f61e),
576 new EmoticonPattern(":-?[0Oo]", 0x1f62e),
577 new EmoticonPattern("\\\\o/", 0x1F631), };
578
579 public static String transformAsciiEmoticons(String body) {
580 if (body != null) {
581 for (EmoticonPattern p : patterns) {
582 body = p.replaceAll(body);
583 }
584 body = body.trim();
585 }
586 return body;
587 }
588}