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