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