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