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