UIHelper.java

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